smashed-egg / laravel-auth-route-bindings
Adds support for creating Route Model bindings to an authenticated user in Laravel
Installs: 1 231
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: ^8.0.2
- illuminate/console: ^9.21|^10.0|^11.0
- illuminate/contracts: ^9.21|^10.0|^11.0
- illuminate/support: ^9.21|^10.0|^11.0
Requires (Dev)
- orchestra/testbench: ^7.6|^8.0|^9.0
- phpunit/phpunit: ^9.5|^10.0
This package is auto-updated.
Last update: 2024-11-15 15:45:41 UTC
README
Laravel Auth Route Bindings
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.
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.