smashed-egg/laravel-auth-route-bindings

Adds support for creating Route Model bindings to an authenticated user in Laravel

1.1.0 2024-03-19 08:03 UTC

This package is auto-updated.

Last update: 2024-11-15 15:45:41 UTC


README

Laravel Auth Route Bindings

Latest Stable Version Downloads this Month

This package allows you to create route model bindings that also use the authenticated user to retrieve the model.

For example. You might want to check that the Post model requested belongs to the User that's logged in. Previously you might have done something like the following:

Route::get('posts/{post}', function (Post $post) {
    abort_unless($post->user_id === auth()->user()->getAuthIdentifier());
    return $post;
});

or

Route::get('posts/{id}', function ($id) {
    $post = Post::where('user_id', auth()->user()->getAuthIdentifier())->findOrFail($id);
    return $post;
});

or using Policies:

<?php
 
namespace App\Policies;
 
use App\Models\Post;
use App\Models\User;
 
class PostPolicy
{
    /**
     * Determine if the given post can be updated by the user.
     */
    public function update(User $user, Post $post): bool
    {
        return $user->id === $post->user_id;
    }
}

Policies have the disadvantage of returning data from the database, hydrating a model, then comparing, and in the case where the user doesn't have access to it, its then thrown away.

This package has the added benefit whereby the logic is done all at the database level.

Requirements

  • PHP 8.0.2+
  • Laravel 9.0+

Installation

To install this package please run:

composer require smashed-egg/laravel-auth-route-bindings

Support Me

Do you like this package? Does it improve you're development. Consider sponsoring to help with future development.

Buy me a coffee!

Thank you!

Usage

You should define your model bindings at the beginning of the boot method of your RouteServiceProvider.

For example:

use App\Models\Post;
use Illuminate\Support\Facades\Route;
 
/**
 * Define your route model bindings, pattern filters, etc.
 */
public function boot(): void
{
    Route::modelAuth('post', Post::class);
 
    // ...
}

And then you can use in your routes declarations the same way as you use other model bindings:

Route::get('posts/{post}', function (Post $post) {
    return $post;
});

You can even use it with scoped bindings:

Route::get('posts/{post}/comments/{comment}', function (Post $post, Comment $comment) {
    //..
})->scopeBindings();

So the Post must belong to the authenticated User, and the Comment must belong to the Post.