Introduction to Laravel's multi-user authentication system
Since Laravel 5.2, the built-in Auth authentication system can support multiple role authentication. That is to say, if you have two roles: administrator and ordinary user, you can achieve authentication through the same Auth system.
This article will give you a detailed introduction to the relevant content of Laravel's multi-user authentication system, and share it for your reference and study. I won't say much below, let's take a look at the detailed introduction.
#1 Automatically generate code
#Laravel’s own Auth can generate related authentication controllers and templates through one line of commands And routing:
php artisan make:auth
This will generate an AuthController authentication controller and HomeController general controller. This controller is of no use. It just jumps after successful login. ;There are also some template files required for login and registration, just look at resource/view; and relevant authentication routes will be generated in the routing file, the source code is in \Illuminate\Routing\Router::auth ();
, in fact, it is configured with some login and registration functions:
public function auth() { // Authentication Routes... $this->get('login', 'Auth\AuthController@showLoginForm'); $this->post('login', 'Auth\AuthController@login'); $this->get('logout', 'Auth\AuthController@logout'); // Registration Routes... $this->get('register', 'Auth\AuthController@showRegistrationForm'); $this->post('register', 'Auth\AuthController@register'); // Password Reset Routes... $this->get('password/reset/{token?}', 'Auth\PasswordController@showResetForm'); $this->post('password/email', 'Auth\PasswordController@sendResetLinkEmail'); $this->post('password/reset', 'Auth\PasswordController@reset'); }
#2 auth.php file configuration
This is a configuration file related to authentication. It is estimated that many people cannot understand some concepts in it, such as guard and provider
, and the documentation is basically not written. . So what exactly is guard? This can be understood as a role. Each item in the guards
array is a role. The default ones are web and api, which means that these two roles currently use the authentication system. Of course, these two will definitely not meet our requirements, so we usually customize some guards. Customization is also very simple, just add an item to the guards array, where the driver indicates how to save the user status for this authentication, usually in the session, and the provider is an item in the provider array below, so what is the provider? Woolen cloth? This is easier to understand. If you want to implement user authentication, you must save the user name and password, right? Then the provider tells Laravel which table your user information is stored in, and the driver tells Laravel which method to use to operate the database.
#3 Authentication
In fact, the code automatically generated by Laravel can already meet the needs of login and registration, but every Each guard requires an AuthController, so how to share an authentication controller? Guard is used here because it can represent the user's identity to perform different logic. However, this guard cannot be obtained in the authentication controller, so we can achieve it through routing parameters. Define a routing group:
Route::group(['prefix'=>'{guard}'],function(){ Route::auth();});
In this routing group we set the prefix to the guard parameter, so that the current guard can be obtained in the AuthController . Under normal circumstances, we obtain routing parameters through dependency injection Request instances, but there is also a pitfall here. That is, before version 5.1, all routing parameters could be obtained through
$request->input('key')
Get it this way, but it no longer works in 5.2. You must get it through
$request->key
, or get it directly from the routing instance, I don’t know What is the reason. Some traits are used in the AuthController controller. These traits implement the logic of authentication registration. You can customize the logic by rewriting some properties of the controller. Including $redirectTo
and $guard
and $username
, etc. At a glance, you can tell that the first one is to jump after successful login, and the second one is Define the guard currently used, and the third one is the username field used for authentication. So we can customize it by obtaining the guard in the authentication controller.
#4 Routing protection
# Generally those who make authentication systems have to protect routes, so how? What about protected routing? The document says to add an auth middleware to the routes that need to be protected, but what is the reality? This is indeed the case, but what the document does not say is that the route protected by auth middleware must also be added with web middleware, must also be added with web middleware, must also be added with web middleware, it is important You have to say things three times, otherwise what problems will arise? Regardless of whether your authentication succeeds or fails, you will jump to the / route. Be careful about this big pitfall! Of course, you can also specify guard in the middleware to let Laravel know which one to authenticate through. If not specified, the default one in the configuration file will be used:
Route::get('profile', [ 'middleware' => 'auth:api', 'uses' => 'ProfileController@show']);
#5 Obtain user instance
After passing the authentication, you can obtain the currently authenticated user instance through the Auth facade.
$user = Auth::user();
Another thing to note here is that the above method obtains the guard in the configuration file by default. If the guard you are currently logged in is not configured In the file, you must get it like this:
$user = Auth::guard('guard')->user();
#6 总结
总得来说,Laravel5.2自带的Auth系统还是很好用的,只是有一些小坑文档没说清楚,用过几次之后就可以很熟悉了,可以给我们节约很多的开发时间。
相关推荐:
The above is the detailed content of Introduction to Laravel's multi-user authentication system. For more information, please follow other related articles on the PHP Chinese website!

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 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



Database operations in PHP are simplified using ORM, which maps objects into relational databases. EloquentORM in Laravel allows you to interact with the database using object-oriented syntax. You can use ORM by defining model classes, using Eloquent methods, or building a blog system in practice.

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

PHP Unit and Integration Testing Guide Unit Testing: Focus on a single unit of code or function and use PHPUnit to create test case classes for verification. Integration testing: Pay attention to how multiple code units work together, and use PHPUnit's setUp() and tearDown() methods to set up and clean up the test environment. Practical case: Use PHPUnit to perform unit and integration testing in Laravel applications, including creating databases, starting servers, and writing test code.

For small projects, Laravel is suitable for larger projects that require strong functionality and security. CodeIgniter is suitable for very small projects that require lightweight and ease of use.
