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.
Simple example
Suppose in the user table, there is a column named admin
, depending on whether the user is an administrator, it can be 1
or 0
. 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 their admin
line set to 1
, 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.
Define the interceptor
To define the interceptor, you can open the App\Providers\AuthServiceProvider.php
file and in our boot ()
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.
Using interceptors
To use interceptors, we can call Gate::allows()
or Gate::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.
Passing data like an interceptor
Suppose our application has a Post table with a column user_id
, It contains the ID of 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 new edit-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 used Route Closures in the example, but we may want to map this route to a controller. This will also let us use the new Authorize function.
Authorize Authorization Helper Function
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 the authorize()
helper to check if the authenticated user has permission to edit the post:
<?php namespace App\Http\Controllers; use App\Models\Post; use Illuminate\Http\Request; class PostController extends Controller { public function edit($id){ $post = Post::find($id); $this->authorize('edit-post', $post); } }
If the controller inherits from the App\Http\Controllers\Controller
base class, you can use the function 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.
Authentication at the view layer
Assume that the Blade view is as follows:
nbsp;html> <meta> <meta> <title>{{ $post->title }}</title> <h1 id="post-gt-title">{{ $post->title }}</h1> <p>{!! $post->body !!}</p>
We can use the Blade helper function@can
Check if the current user is allowed to edit this post:
nbsp;html> <meta> <meta> <title>{{ $post->title }}</title> <h1 id="post-gt-title">{{ $post->title }}</h1> <p>{!! $post->body !!}</p> @can('edit-post', $post) id }}">Edit Post @endcan
If the authenticated user is the original author of the post, they will see an Edit Post button.
Using the @can
helper function can make our code easier to read and manage. You can also use @cannot
to reverse the operation.
Summary
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, Interceptors are 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!

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

Laravel is a modern PHP framework that provides a powerful tool set, simplifies development processes and improves maintainability and scalability of code. 1) EloquentORM simplifies database operations; 2) Blade template engine makes front-end development intuitive; 3) Artisan command line tools improve development efficiency; 4) Performance optimization includes using EagerLoading, caching mechanism, following MVC architecture, queue processing and writing test cases.

Laravel's MVC architecture improves the structure and maintainability of the code through models, views, and controllers for separation of data logic, presentation and business processing. 1) The model processes data, 2) The view is responsible for display, 3) The controller processes user input and business logic. This architecture allows developers to focus on business logic and avoid falling into the quagmire of code.

Laravel is a PHP framework based on MVC architecture, with concise syntax, powerful command line tools, convenient data operation and flexible template engine. 1. Elegant syntax and easy-to-use API make development quick and easy to use. 2. Artisan command line tool simplifies code generation and database management. 3.EloquentORM makes data operation intuitive and simple. 4. The Blade template engine supports advanced view logic.

Laravel is suitable for building backend services because it provides elegant syntax, rich functionality and strong community support. 1) Laravel is based on the MVC architecture, simplifying the development process. 2) It contains EloquentORM, optimizes database operations. 3) Laravel's ecosystem provides tools such as Artisan, Blade and routing systems to improve development efficiency.

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

Building user login capabilities in Laravel is a crucial task and this article will provide a comprehensive overview covering every critical step from user registration to login verification. We will dive into the power of Laravel’s built-in verification capabilities and guide you through customizing and extending the login process to suit specific needs. By following these step-by-step instructions, you can create a secure and reliable login system that provides a seamless access experience for users of your Laravel application.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment