search
HomePHP FrameworkLaravelWhat is guard in laravel

In laravel, guard is a plug-in for user authentication; the role of guard is to process authentication and judge each request, read data from the database and compare it with user input, and determine whether the call has been logged in or allowed to pass , and Guard can very flexibly build its own certification system.

What is guard in laravel

The operating environment of this article: Windows 10 system, Laravel version 5.4, Dell G3 computer.

guard in laravel

In fact, you can understand whether it is Guard or Provide. A plug-in for a specific function.

His role is to process an authentication to determine whether each request or call has been logged in or allowed to pass.

What is Guard

In the Laravel/Lumen framework, user login/registration authentication has basically been encapsulated and can be used out of the box. The core of login/registration authentication is:

Storing the user’s registration information into the database (registration)

Reading data from the database and comparing it with user input (authentication)

The above two steps are the basics of login/registration. You can see that they will involve database operations. The bottom layer of the framework has already done this for us, and has taken into account many situations. For example, the data table for user authentication is not the user table but the user table. admin_user, the authentication field is phone instead of email, and other issues that Guard needs to solve. Through Guard, you can specify which data table and fields to use, etc. Guard can build your own authentication system very flexibly.

In layman’s terms, it’s like this: Guard is like the gatekeeper of a community, ruthless and does not recognize people but only registration information.

Before entering the community, the uncle needs to check your identity. If the verification fails, the uncle will not let you in.

If you are walking/biking in, Uncle 1 needs to check your access card. He takes out the book that records the access card information of all owners in the community to see if your access card information is in this book;

If you drive in, Uncle 2 will check your license plate number from the book that records the license plate numbers of all owners. Therefore, when the new owner moves into the community, he needs to inform the doorman uncles of your access card information or license plate number. Otherwise, Uncle 2 won’t let you in.

If the property manager wants to enter the community, the doorman uncle 3 will only recognize the registration information. The manager will show his manager access card, and the doorman uncle will check the book that records the manager's access card information.

The above corresponds to the multi-user authentication in the framework:

People walking/cycling-> Access card

People driving-> License plate number

Property Manager-> Access Card

Access card and license plate number are different authentication methods, and the book viewed by the guard uncle corresponds to the user information in different databases. In this way, Isn't it easier to understand.

Lumen/Laravel provides very flexible authentication in the form of middleware, and multiple authentications can be switched through simple configuration.

The workflow diagram is as follows:

What is guard in laravel

As you can see from the picture, a Guard involves three parts, namely:

  • Guard implementation itself

  • User Provider user provider, specify which data table and how to obtain (eloquent/database)

  • The Authenticatable interface stipulates those things that can be authenticated, which is the interface that implements it.

Extended knowledge:

Guard My understanding is that it should be something similar to user authentication.

There are parameters for configuring guards in config/auth.php. It can be seen that web and api are two guards.

In daily business, API may be more of a front-end user's operation, while web is more of a back-end user's operation.

The default configuration points to the provider of users.

/*
    | Authentication Guards
    |认证关卡
    | Next, you may define every authentication guard for your application. Of course, a great default configuration has been defined for you here which uses session storage and the Eloquent user provider.
    |接下来,你可能要为你的应用定义每个认证关卡。当然,已经为你定一了一个很不错的默认配置。这里会使用会话储存和用户模型
    | All authentication drivers have a user provider. This defines how the users are actually retrieved out of your database or other storage mechanisms used by this application to persist your user's data.
    |所有的认证驱动都有一个用户提供者。这里定义了怎么实际上怎么从你的数据库或者其他储存机制中取出用户。以便应用开保持你的用户数据
    | Supported: "session", "token"
    |可选驱动:"session", "token"
    */
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],

Next, let’s take a look at the configuration of the provider.

  /*
    | User Providers
    |用户提供者
    | If you have multiple user tables or models you may configure multiple sources which represent each model / table. These sources may then be assigned to any extra authentication guards you have defined.
    | 如果你有多个用户表或用户模型,你可以配置多个代表用户表或模型的资源。这些资源可能被分配给应用中你定义的其他认证关卡
    | Supported: "database", "eloquent"
    |
    */
 'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

In providers, you have the users configuration you just saw. This is the user group for configuring laravel, because under normal circumstances, front-end and back-end users operate separately. So you can create a new admin user group here and configure it. Out of the box, only users is used by default.

The corresponding password operations for each user group should be different, so there is also password configuration here.

  /*
    | Resetting Passwords
    | 密码重置
    | You may specify multiple password reset configurations if you have more than one user table or model in the application and you want to have separate password reset settings based on the specific user types.
    | 如果你有多个用户模型或表,并且想对不同用户类型有特定的密码重置,则可以配置多个特定的重置密码
    | The expire time is the number of minutes that the reset token should be considered valid. This security feature keeps tokens short-lived so they have less time to be guessed. You may change this as needed.
    |这个获取时间是令牌过期的分钟数,这个安全措施可以保证令牌保持段时间有效,因此有更少的时间被破解。你可以按照需要更改。
    */
    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

We usually use Auth::check() to detect logged-in users, or whether the user is logged in. This is because when using the default configuration, guard is automatically configured as users. Group.

  /*
    | Authentication Defaults
    | 默认认证配置
    | This option controls the default authentication "guard" and password reset options for your application. You may change these defaults as required, but they're a perfect start for most applications.
    | 这个就是应用的默认认证关卡个重置密码,你可以按自己要求更改。但这是最适合一个新应用的配置
    */
    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

The web guard points to the users model.

But if we have two user groups, the front and backend, how to verify it?

Auth::check() is a method to determine whether the user is logged in. If the default user system is used, then there is no problem in using it this way.

But if you use two groups of users, you should do this:

Auth::guard('api')->check() is used to determine whether the front-end user is logged in to Auth:: guard('web')->check() is used to determine whether the background user is logged in

So if you use a non-default user group, you need to specify it with guard.

So what we usually use is actually the default configuration. To write it all, it should be Auth::guard('web)->check()

[Related recommendations: laravel video Tutorial

The above is the detailed content of What is guard in laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Laravel's Primary Function: Backend DevelopmentLaravel's Primary Function: Backend DevelopmentApr 15, 2025 am 12:14 AM

Laravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.

Laravel's Backend Capabilities: Databases, Logic, and MoreLaravel's Backend Capabilities: Databases, Logic, and MoreApr 14, 2025 am 12:04 AM

Laravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.

Laravel's Versatility: From Simple Sites to Complex SystemsLaravel's Versatility: From Simple Sites to Complex SystemsApr 13, 2025 am 12:13 AM

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

Laravel (PHP) vs. Python: Development Environments and EcosystemsLaravel (PHP) vs. Python: Development Environments and EcosystemsApr 12, 2025 am 12:10 AM

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

Laravel and the Backend: Powering Web Application LogicLaravel and the Backend: Powering Web Application LogicApr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Why is Laravel so popular?Why is Laravel so popular?Apr 02, 2025 pm 02:16 PM

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Which is better, Django or Laravel?Which is better, Django or Laravel?Mar 28, 2025 am 10:41 AM

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

Which is better PHP or Laravel?Which is better PHP or Laravel?Mar 27, 2025 pm 05:31 PM

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment