Home>Article>PHP Framework> Let’s talk about interceptors (Gates) in Laravel
Laravel Gates (interceptors) allow you to authorize users to access certain areas of your application. You can easily define interceptors in your application and then use them to allow or deny access.
Suppose in the user table, there is a column namedadmin
, depending on whether the user is an administrator, it can be1
or0
. We can easily secure a module that is part of the application with a simple check like this:
Route::get('administration', function(){ if(auth()->check() && auth()->user()->admin){ echo 'Welcome to the admin section'; } else { echo 'You shall not pass'; } });
If a specific user has theiradmin
line set to1
, they will see the following output.
Otherwise, they will see the following:
This looks great right! We have an easy way to allow or deny access to specific parts of our application. However, the problem is: what if there are a large number of places throughout the application where user access permissions need to be checked and modified. We would have to search the code globally and modify this logic everywhere. Not very efficient.
For this, we can define a Gate (interceptor) and use it throughout the application.
To define the interceptor, you can open theApp\Providers\AuthServiceProvider.php
file and in ourboot ()
Add the following content to the method:
public function boot() { $this->registerPolicies(); Gate::define('access-admin', function ($user) { return $user->admin; }); }
We can use this interceptor anywhere in the entire application where we want to authenticate the administrator user. In the next section you'll see how we use this new interceptor.
To use interceptors, we can callGate::allows()
orGate::denies( )
method, as shown below:
Route::get('administration', function(){ if (Gate::allows('access-admin')) { echo 'Welcome to the admin section'; } else { echo 'You shall not pass'; } });
Please note:
Gate::denies()
method will doGate::allows()
The benefit of performing a reverse check
interceptor is that we can now change our definition at any time and the authorization logic will be changed synchronously throughout the application.
Another purpose of using interceptors is to check permissions related to data. Taking a blog as an example, we can grant users editing permissions on posts they create.
We can pass data to the interceptor to check if the user has permission to perform an action.
Suppose our application has aPosttable with a columnuser_id
, It contains theIDof the user who created it. We can define a Gate (interceptor) to determine if a user can edit a specific post like this:
Gate::define('edit-post', function ($user, $post) { return $user->id === $post->user_id; });
Two parameters are passed to our interceptor definition. The first is the$user
object, which contains the authenticated user, and the second parameter is our$post
object.
Tips: If there is no authenticated user, the interceptor will return false.
The interceptor will allow access if the authenticated user is the original author; otherwise it will deny access.
Here's a quick example of how we can use the newedit-post
interceptor.
Route::get('edit/{id}', function($id){ $post = \App\Model\Post::find($id); if( Gate::allows('edit-post', $post) ){ echo 'You can edit this post'; } else { echo 'You shall not pass'; } });
Above, we usedRoute Closuresin the example, but we may want to map this route to a controller. This will also let us use the newAuthorizefunction.
In addition to efficiency, another reason to use interceptors is the helper function.
Assume we map the route to the controller:
Route::get('edit/{id}', 'PostController@edit');
We can use theauthorize()
helper to check if the authenticated user has permission to edit the post:
authorize('edit-post', $post); } }
If the controller inherits from theApp\Http\Controllers\Controller
base class, you can use thefunction just like the
Gate::allow()function authorize()
Helper function.
Finally, what if we want to check authorization in the view? We can do this using the@can
Blade function helper.
Assume that the Blade view is as follows:
nbsp;html>{{ $post->title }} {{ $post->title }}
{!! $post->body !!}
We can use the Blade helper function@can
Check if the current user is allowed to edit this post:
nbsp;html>{{ $post->title }} {{ $post->title }}
{!! $post->body !!}
@can('edit-post', $post)id }}">Edit Post@endcan
If the authenticated user is the original author of the post, they will see anEdit Postbutton.
Using the@can
helper function can make our code easier to read and manage. You can also use@cannot
to reverse the operation.
This is the basics of using Gates (interceptors) in Laravel applications. Interceptors allow us to easily authorize specific users to access areas of our application. This may also be called an Access Control List (ACL), a list of permissions associated with an object.
But we shouldn't overcomplicate things... In the simplest scenario,Interceptorsare used to allow or deny access. Users can either be allowed authorization or be denied authorization.
Since this tutorial is about getting the user through and not through... it makes sense to send you out with this image of Gandalf from Lord of the Rings (manual dog head).
To learn more about Laravel Gates (interceptors), be sure to visit the Larav authorization documentation.
English original address: https://devdojo.com/tnylea/laravel-gates
Translation address: https://learnku.com/laravel/t/67585
[Related recommendations:laravel video tutorial]
The above is the detailed content of Let’s talk about interceptors (Gates) in Laravel. For more information, please follow other related articles on the PHP Chinese website!