Laravel 5.2 new features multi-user authentication

Source: Internet
Author: User
Tags auth php code

Laravel 5.2 now supports multi-user authentication, which allows logon authentication for different data table users (such as front-end users and back-end users. Next we will briefly introduce the implementation of multi-user login and registration functions.

1. Generate certification scaffolding

First, use the authentication scaffolding provided by Laravel 5.2 to complete initialization:

Php artisan make: auth

The Artisan command generates the routes, views, and HomeController required for user authentication:

View the route file routes. php and you will find that the file has been updated:

Route: group (['middleware Ware '=> 'web'], function (){
Route: auth ();
Route: get ('/home', 'homecontroller @ index ');
});
Here, Route: auth () defines the registered logon Route./home is the Route entry after the authentication is passed.

2. Implement logon for foreground users

Next, we will first implement the login of the front-end User, that is, the User login that comes with Laravel. Through the scaffolding above, we have generated all the code required for authentication, and the rest is to use the migration command to create a user authentication table:

Php artisan migrate

After the command is executed, the users table and password_resets table are generated, respectively, the user-owned table and the password reset table.

Then we can enter http://laravel.app/registerin the browser to register a new user:

Create a user named test. After successful registration, go to http://laravel.app/homeand you will find that the user has gone through:

3. Edit the authentication configuration file

To implement multi-user authentication, you must first configure the authentication configuration file auth. php. Here we implement the function of the frontend and backend user logon, so the corresponding configuration is as follows:

<? Php

Return [

'Defaults' => [
'Guard '=> 'web ',
'Password' => 'users ',
],

& Apos; guards & apos; = & apos [
'Web' => [
'Driver '=> 'session ',
'Provider' => 'users ',
],
'Admin' => [
'Driver '=> 'session ',
'Provider' => 'admins ',
],
'Api' => [
'Driver '=> 'token ',
'Provider' => 'users ',
],
],

'Providers '=> [
'Users' => [
'Driver '=> 'eloquent ',
'Model' => App \ User: class,
],
'Admins' => [
'Driver '=> 'eloquent ',
'Model' => App \ Admin: class,
],
],

'Password' => [
'Users' => [
'Provider' => 'users ',
'Email '=> 'auth. emails. Password ',
'Table' => 'Password _ resets ',
'Expire '=> 60,
],
],
];

Authentication consists of guard and provider (refer to the user authentication document). Therefore, the admin and admins options are added in these two configuration items.

4. Create a background user model

Next we will implement background user logon. First, use the following Artisan command to generate the background user model:

Php artisan make: model Admin -- migration
With the -- migration option, the corresponding user table admins will be generated. We define that the fields of this data table are the same as those of users:

Schema: create ('admins', function (Blueprint $ table ){
$ Table-> increments ('id ');
$ Table-> string ('name ');
$ Table-> string ('email ')-> unique ();
$ Table-> string ('password', 60 );
$ Table-> rememberToken ();
$ Table-> timestamps ();
});

Run the migration command to generate the table:


Php artisan migrate

Then update the Admin model class as follows:

<? Php

Namespace App;

Use Illuminate \ Foundation \ Auth \ User as Authenticatable;

Class Admin extends Authenticatable
{
/**
* The attributes that are mass assignable.
     *
* @ Var array
*/
Protected $ fillable = [
'Name', 'Email ', 'password ',
];

/**
* The attributes excluded from the model's JSON form.
     *
* @ Var array
*/
Protected $ hidden = [
'Password', 'Remember _ token ',
];
}

5. Define Backend User Authentication routes and controllers

Next, let's define the background user authentication route. Modify the routes. php code as follows:

Route: group (['ddleware '=> ['web'], function (){

Route: auth ();
Route: get ('Home', 'homecontroller @ index ');

Route: get ('admin/login', 'admin \ AuthController @ getlogin ');
Route: post ('admin/login', 'admin \ AuthController @ postlogin ');
Route: get ('admin/register ', 'admin \ AuthController @ getRegister ');
Route: post ('admin/register ', 'admin \ AuthController @ postRegister ');
Route: get ('admin', 'admincontroller @ index ');

});

Then use the Artisan command to create the corresponding controller:

Php artisan make: controller Admin/AuthController
Php artisan make: controller AdminController

Edit the Admin/AuthController. php code as follows:

<? Php

Namespace App \ Http \ Controllers \ Admin;

Use App \ Admin;
Use Validator;
Use App \ Http \ Controllers \ Controller;
Use Illuminate \ Foundation \ Auth \ ThrottlesLogins;
Use Illuminate \ Foundation \ Auth \ AuthenticatesAndRegistersUsers;

Class AuthController extends Controller
{
Use AuthenticatesAndRegistersUsers, ThrottlesLogins;

Protected $ redirectTo = '/admin ';
Protected $ guard = 'admin ';
Protected $ loginView = 'admin. Login ';
Protected $ registerView = 'admin. register ';

Public function _ construct ()
    {
$ This-> middleware ('guest: admin', ['logout t' => 'logout']);
    }

Protected function validator (array $ data)
    {

Return Validator: make ($ data ,[
'Name' => 'required | max: 255 ',
'Email '=> 'required | email | max: 255 | unique: admins ',
'Password' => 'required | confirmed | min: 6 ',
]);

    }

Protected function create (array $ data)
    {
Return Admin: create ([
'Name' => $ data ['name'],
'Email '=> $ data ['email'],
'Password' => bcrypt ($ data ['password']),
]);

    }

}

Edit the AdminController. php code as follows:

<? Php

Namespace App \ Http \ Controllers;

Use Illuminate \ Http \ Request;

Use App \ Http \ Requests;
Use App \ Http \ Controllers \ Controller;
Use Auth;

Class AdminController extends Controller
{

Public function _ construct ()
    {
$ This-> middleware ('auth: admin ');
    }

Public function index ()
    {
$ Admin = Auth: guard ('admin')-> user ();
Return $ admin-> name;
    }

}
6. Create and modify view files

Finally, we need to create a view file for background user authentication. Here we simply copy the foreground user view template and make some modifications:

Cp-r resources/views/auth resources/views/admin

Modify the logon and registry ticket submission addresses in the resources/views/admin Directory:

/Login->/admin/login
/Register->/admin/register

7. Implement background user authentication

Visit http://laravel.app/admin/registerin the browser to display the registration page in the same way:

Register a user whose username is admin. After successful registration, the page will jump to http://laravel.app/admin, indicating that the certification is successful.

Now, we have completed the login authentication function for both front-end and back-end users.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.