Download the PHP package michaeljennings/route-guards without Composer
On this page you can find all versions of the php package michaeljennings/route-guards. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download michaeljennings/route-guards
More information about michaeljennings/route-guards
Files in michaeljennings/route-guards
Package route-guards
Short Description Provides a convenient place to authorize routes when model policies cannot be used
License MIT
Informations about the package route-guards
Route Guards
Installation
To install the package run
Once the package is installed, add the MichaelJennings\RouteGuards\GuardRoutes
middleware to you App\Http\Kernel.php
,
if you are using model bindings makes ure to register it after the SubstituteBinding
middleware.
Usage
Registering Guards
You can guard a route in 3 different ways.
Firstly, you can chain a guard method on the route.
Or you can set the guard in the route action.
Finally, you can specify the guard in a route group.
Writing Guards
By default we will try to hit an authorize method on the route guard. The authorize method should return true if the user is allowed to access the route, and false if they aren't.
Occasionally you might want to authorize one endpoint in a group differently to the others. For example, in the below routes we want to check for a different to view the products and to create a product
To do this simply add a method with the same name as the controller method to your route guard.
Model Bindings
For certain routes you may also want to check that a user can access a specific record, for example in the route below we want to make sure the user can access a record before they can make updates to it.
By default we will attempt to use model bindings to access the model from the route and pass it into the authorize method.
Custom Bindings
If you aren't using model bindings but still want to take advantage of finding your resource in the route guard you
can override the find
method.
Using Multiple Guards
In the route below we have to parameters in one route that need to be guarded differently.
We can do this by setting two guards on the route, and telling them which parameter they guard.
You can also define this on a route group by providing an array where the key is the parameter the guard will protect.
Customising Exceptions
If authorization fails we will throw the Illuminate\Auth\Access\AuthorizationException
exception. If you want to
change this you can override the authorizationFailed
method.
Occasionally you might want to throw a different exception for your index endpoint than your create endpoint. You can this by taking the name of the method and adding failed to it.