Laravel 5.2 User Registration and login

Source: Internet
Author: User
laravel5.2 verification has changed, added a call guard, this thing is mainly responsible for checking the user's session and the like

It is mentioned in the original: https://laravel.com/docs/5.2/authentication#introduction

At its core, Laravel ' s authentication facilities is made up of "guards" and "providers". Guards define how users is authenticated for each request. For example, Laravel ships with a session guard which maintains state using session storage and cookies and a token guard, Which authenticates users using a "API token" that is passed with each request.

This command automatically creates some validation-related files Resources/views/auth and resources/views/layouts, but we don't need to understand the process first.

PHP Artisan Make:auth

Arrange the routing table beforehand

App/http/routes.phproute::group ([' middleware ' + = [' web ']], function () {    route::resource ('/articles ', ' Articlescontroller ');    Route::get (' Auth/login ', ' auth\authcontroller@getlogin '); Open the login page with Get    Route::p ost (' Auth/login ', ' auth\authcontroller@postlogin '),//Submit the Postlogin method to the login page, In fact is to give Auth\authcontroller postlogin    route::get (' Auth/register ', ' auth\authcontroller@getregister ');//Similar    Route::p ost (' Auth/register ', ' auth\authcontroller@postregister ');//similar to    route::get (' auth/logout ', ' auth\ Authcontroller@getlogout '); Logout separate out separately, is also a similar way to use//        route::get (' Auth/logout ', function () {//            auth::logout ()//        });});

Need to explain:

1. The above in Laravel 5.2 is to be included in the web of this middleware [' Middleware ' and ' [' web '], in addition to CSRF, there are some validation logic is associated.

2. Login and register are in the "protection", and logout is not, specifically can see authcontroller.php, mainly because logout more casual, and can not use the session to restrict their access

3. None of the above routes are provided by default and require your own handwriting, mainly because Laravel 5.2 is not available at the beginning, but because of this, the whole process is clearly sorted out

4. Laravel This default login registration needs to be associated with the model, if the model has a problem, it will also affect the entire process, laravel a lot of things are packaged, for the average person, it is not easy to know how the process in effect, the need to constantly study the source of learning.

This is the process diagram I understand.

First Look at Authcontroller

app/http/controllers/auth/authcontroller.php<? phpnamespace app\http\controllers\auth;use App\User;use Validator;use App\http\controllers\controller;use Illuminate\foundation\auth\throttleslogins;use Illuminate\ Foundation\auth\authenticatesandregistersusers;class Authcontroller extends controller{/* |----------------------- ---------------------------------------------------    |    Registration & Login Controller |--------------------------------------------------------------------------| | This controller handles the registration of new users, as well as the | Authentication of existing users. By default, this controller uses | A simple trait to add these behaviors.    Why don ' t you explore it?    |  */Use Authenticatesandregistersusers, throttleslogins;     Using these 2 classes as the primary validation function class, the following will say/** * Where to redirect the users after Login/registration.  * * @var String */protected $redirectTo = '/';    This is a redirect link for successful login, and sometimes it needs to be modified. /** * Create a NEW Authentication controller instance.  * * @return void */Public function __construct () {$this->middleware ($this->guestmiddleware (),   [' except ' = ' logout ']);     Excludes logout, is not within the scope of middleware protection}/** * Get a validator for an incoming registration request. * * @param array $data * @return \illuminate\contracts\validation\validator */protected function Validat            or (array $data)//There is a validation logic here, request validation There are 2 ways, one is to write the request file, one is to use Validator {return validator::make ($data, [ ' Name ' = ' required|max:255 ', ' email ' = ' required|email|max:255|unique:users ', ' Pass        Word ' + ' required|min:6|confirmed ',//default has these validation logic, this logic is fastidious, because the default Laravel authentication registration login is associated here.    ]);     }/** * Create A new user instance after a valid registration. * * @param array $data * @return User */protected function Create (array $data)//This is create, inside the function body is the use of M Odel create method, directly in the database to generate data {REturn user::create ([' name ' = ' = ' $data [' name '], ' email ' = ' + ' $data [' email '], ' password '    = = Bcrypt ($data [' Password ']),]); }}

And then we look at authenticatesandregistersusers.

vendor/laravel/framework/src/illuminate/foundation/auth/authenticatesandregistersusers.php<? phpnamespace illuminate\foundation\auth;trait authenticatesandregistersusers{use    authenticatesusers, RegistersUsers {// Here is the focus, the use of two classes, one is to authenticate users, one is registered users        authenticatesusers::redirectpath insteadof registersusers;          Authenticatesusers::getguard insteadof registersusers;    }}

And then we'll see Authenticatesusers.

Because we write on the route to call Getlogin,postlogin,getregister,postregister, and Authenticatesusers is the main processing getlogin,postlogin.

vendor/laravel/framework/src/illuminate/foundation/auth/authenticatesusers.php
 Showloginform ();     }/** * Show the application login form. * * @return \illuminate\http\response */Public Function showloginform ()//actually call this showloginform {$vi ew = property_exists ($this, ' LoginView ')?        $this->loginview: ' Auth.authenticate ';        if (view ()->exists ($view)) {return view ($view); } return view (' Auth.login '); See here can see, determine whether there is auth.authenticate file, if not the Auth.login, this file is actually the views folder under the blade file, that is resources/views/auth/     login.blade.php}/** * Handle a login request to the application. * * @param \illuminate\http\request $request * @return \illuminate\http\response */Public function Postl    Ogin (Request $request)//Here is Postlogin {return $this->login ($request);     }/** * Handle a login request to the application. * * @param \illuminate\http\request $request * @return \illuminate\http\response */Public Function Login (Request $rEquest)//actually calls the login {$this->validatelogin ($request); If the class is using the throttleslogins trait, we can automatically throttle//The login attempts for this AP Plication.        We ' ll key this by the username and//The IP address of the client making these requests to this application.  $throttles = $this->isusingthrottlesloginstrait (); This is the interpretation of the frequency of user login related if ($throttles && $lockedOut = $this->hastoomanyloginattempts ($request)) {//Here is a more detailed            The Toomanylogin $this->firelockoutevent ($request);        return $this->sendlockoutresponse ($request);  } $credentials = $this->getcredentials ($request);        Here is to confirm whether the user has logged in, will be related to remember, is to avoid landing related. if (Auth::guard ($this->getguard ())->attempt ($credentials, $request->has (' remember ')) {return $this-&        Gt;handleuserwasauthenticated ($request, $throttles); }//If The login attempt was unsuccessful we'll increment tHe number of attempts//to login and redirect the user back to the login form.        Of course, when this//user surpasses their maximum number of attempts they would get locked out.        if ($throttles &&! $lockedOut) {$this->incrementloginattempts ($request);    } return $this->sendfailedloginresponse ($request);     }/** * Validate the user login request. * * @param \illuminate\http\request $request * @return void */protected function Validatelogin (Request $ Request) {$this->validate ($request, [$this->loginusername () = ' required ', ' Password ' =&gt ;    ' Required ',]);     }/** * Send The response after the user is authenticated.     * * @param \illuminate\http\request $request * @param bool $throttles * @return \illuminate\http\response */protected function handleuserwasauthenticated (Request $request, $throttles) {if ($throttles) {           $this->clearloginattempts ($request); } if (Method_exists ($this, ' authenticated ')) {return $this->authenticated ($request, Auth::guard ($thi        S->getguard ())->user ());    } return redirect ()->intended ($this->redirectpath ());     }/** * Get the failed login response instance. * * @param \illuminate\http\request $request * @return \illuminate\http\response */protected function Sen Dfailedloginresponse (Request $request) {return redirect ()->back ()->withinput ($request->onl Y ($this->loginusername (), ' Remember '))->witherrors ([$this->loginusername ()] = $thi    S->getfailedloginmessage (),]);     }/** * Get the failed login message.                * * @return String */protected function getfailedloginmessage () {return Lang::has (' auth.failed ') ? Lang::get (' auth.failed '): ' These CREDentials does not match our records. ';     }/** * Get the needed authorization credentials from the request.  * * @param \illuminate\http\request $request * @return Array */protected function getcredentials (Request    $request) {return $request->only ($this->loginusername (), ' Password ');     }/** * Log the user out of the application.    * * @return \illuminate\http\response */Public Function getlogout () {return $this->logout ();     }/** * Log the user out of the application. * * @return \illuminate\http\response */Public Function logout () {Auth::guard ($this->getguard ())        ->logout ();    Return Redirect (Property_exists ($this, ' redirectafterlogout ')? $this->redirectafterlogout: '/');     }/** * Get The guest middleware for the application.        */Public Function Guestmiddleware () {$guard = $this->getguard (); Return $guard? ' Guest: '. $guard : ' Guest ';     }/** * Get the login username to being used by the controller. * * @return String */Public Function Loginusername () {return property_exists ($this, ' username ')? $    This->username: ' Email ';     }/** * Determine if the class is using the Throttleslogins trait. * * @return BOOL */protected function isusingthrottlesloginstrait () {return In_array (Th    Rottleslogins::class, Class_uses_recursive (Static::class));     }/** * Get the guard to be used during authentication. * * @return String|null */protected function Getguard () {return property_exists ($this, ' Guard ')? $    this->guard:null; }}

And then we'll see registersusers.php.

This main treatment getregister,postregister

vendor/laravel/framework/src/illuminate/foundation/auth/registersusers.php<? phpnamespace Illuminate\ Foundation\auth;use illuminate\http\request;use illuminate\support\facades\auth;trait RegistersUsers{use    Redirectsusers;     /** * Show the application registration form. * * @return \illuminate\http\response */Public Function Getregister ()//This is Getregister {return $th    Is->showregistrationform ();     }/** * Show the application registration form. * * @return \illuminate\http\response */Public Function showregistrationform ()//is actually called by him {if (prop        Erty_exists ($this, ' Registerview ') {return view ($this->registerview);  } return view (' Auth.register '); See the logic can know, if not registerview to use Auth.register as the registration page, the principle is similar to login}/** * Handle A registration request for the APPL     Ication. * * @param \illuminate\http\request $request * @return \illuminate\http\response */public FUnction Postregister (Request $request)//Here is Postregister {return $this->register ($request);     }/** * Handle A registration request for the application. * * @param \illuminate\http\request $request * @return \illuminate\http\response */Public function Regis          ter (Request $request)//actually use him, here is a bit complex {$validator = $this->validator ($request->all ()); if ($validator->fails ()) {//will first determine whether it is possible to pass validator, And this validator is the one before the authcontroller.php, and this throwvalidationexception (not in the page display error//IS here        Storage/logs/laravel.log $this->throwvalidationexception ($request, $validator);         } auth::guard ($this->getguard ())->login ($this->create ($request->all ())); Here by calling Getguard to determine whether to confirm the write to the database, here first through create to write to the database, and then log in login, login success, is the following callback page.        So ingenious. Return Redirect ($this->redirectpath ()); The callback page that registered successfully returned is also in authcontroller.php with}/**     * Get the Guard to be used during registration. * * @return String|null */protected function Getguard () {return property_exists ($this, ' Guard ')? $  this->guard:null;    This is to judge the guard in the auth.php. }}

then we configure the login page

resources/views/auth/login.blade.php@extends (' Layout.app ') @section (' content ') { !!  Form::open ([' url ' = ' auth/login ')]! Here to match the routing table configuration, post submitted to Auth/login!--Email Field---> {!!     Form::label (' email ', ' email: ')! There are 2 login entries, one is email one is password {!!!                
 Form::email (' email ', NULL, [' class ' = ' Form-control '])! !--Password Field---> {!!            Form::label (' Password ', ' Password: ')!! {!!                Form::p assword (' Password ', [' class ' = ' Form-control '])! {!!        Form::submit (' login ', [' class ' = ' btn btn-primary form-control '])! {!!        
 Form::close ()!!} 
  
  
    //This code is extra, mainly in order to see the error message when the verification fails, Laravel will write the wrong information into the $errors, so it can be seen on the page @foreach ($errors-& Gt;all () as $error)
  • {{$error}}
  • @endforeach
@stop

Then we configure the registration page

Here we have 4 fields, there are 3 things to be, name,password,email, because this corresponds to the value of the Authcontroller create method, in fact, this is also related to the model table, Because our user table uses these 3 fields for validation.

Resources/views/auth/register.blade.php@extends (' Layout.app ') @section (' content ') {!!  Form::open ([' url ' = ' auth/register ')]! Note that this is post to Auth/register
 {!!                Form::label (' name ', ' Name: ')!!} {!! Form::text (' name ', null, [' class ' = ' Form-control '])!
 {!!            Form::label (' email ', ' email: ')! {!! Form::email (' email ', NULL, [' class ' = ' Form-control '])!
 {!!            Form::label (' Password ', ' Password: ')!! {!! Form::p assword (' Password ', [' class ' = ' Form-control '])!
 {!!  Form::label (' password_confirmation ', ' password_confirmation: ')!! Note that this password_confirmation is fastidious, if not written in this way, will lead to validator verification does not pass {!!                Form::p assword (' password_confirmation ', [' class ' = ' Form-control '])! {!!        Form::submit (' register ', [' class ' = ' btn btn-primary form-control '])! {!! Form::close ()!!}
 
 
      @foreach ($errors->all () as $error)
    • {{$error}}
    • @endforeach
@stop

And then we look at authenticatesusers.php.

vendor/laravel/framework/src/illuminate/foundation/auth/authenticatesusers.php Public    function GetLogout ()   //This is Getlogout    {        return $this->logout ();    }    /**     * Log The user out of the application.     *     * @return \illuminate\http\response     *    /Public Function logout ()  //is actually he    {        Auth::guard ($this->getguard ())->logout ();        Return Redirect (Property_exists ($this, ' redirectafterlogout ')? $this->redirectafterlogout: '/auth/login ');          It should be noted here that the logout redirect address here needs to be set, the default is/But if you want to log in to see, then there will be an error.    }

And then we'll see authcontroller.php.

app/http/controllers/auth/authcontroller.php    protected $redirectTo = '/articles ';//Just now we mentioned that the redirect address for successful login is this $ Redirectto    protected $guard = ' web ';  This guard is special, because of the laravel5.2 relationship.

An explanation of this website

Guard Customizationyou may also customize the ' guard ' that's used to authenticate users. To get started, define a guard property on your authcontroller. The value of this property should correspond and one of the guards configured in your auth.php configuration File:protect ed $guard = ' admin ';

You want to set a guard value, and you want to correspond with auth.php, and then we'll look at auth.php.

config/auth.php<? Phpreturn [/* |--------------------------------------------------------------------------|    Authentication Defaults |--------------------------------------------------------------------------| | This option controls the default authentication "guard" and password | Reset options for your application. Change these defaults |    As required, but they ' re a perfect the start for the most applications.    |    */' defaults ' = [' guard ' + ' web ',//default specifies a guard is called the Web ' passwords ' + ' users ',],/* |--------------------------------------------------------------------------    |    Authentication Guards |--------------------------------------------------------------------------| |    Next, define every authentication guard for your application. | Of course, a great default configuration have been defined for you |    Here which uses session storage and the eloquent user provider.    | | All AuthenTication drivers has a user provider. This defines how the | Users is actually retrieved out of your database or other storage |    Mechanisms used by this application to persist your user ' s data.    | |    Supported: "Session", "token" | */' guards ' + [' web ' = = And then this is called the Web Guard there are driver and provider these attributes, one is session driver, one is the provider of users, simple understanding is to use        Users table and session to do guard, this guard can be understood as the verification of ' driver ' = ' session ', ' provider ' and ' users ', ' API ' = [' Driver ' = ' token ', ' provider ' = ' users ',], '/* |---- ----------------------------------------------------------------------    |    User Providers |--------------------------------------------------------------------------| | All authentication drivers has a user provider. This defines how the | Users is actually retrieved out of your database or other storage | Mechanisms used by this application to persist your user 's data.    | | If you have multiple user tables or models your may configure multiple | Sources which represent each model/table. These sources May and then |    be assigned to any extra authentication guards you have defined.    | |    Supported: "Database", "eloquent" | */' providers ' + [' users ' = [//] Here again explains the provider of users is a eloquent, the model users ' driver ' = ' eloquent ', ' model ' = + App\user::class,],//' users ' and ' [//' Driver ' =&G T ' Database ',//' table ' = ' users ',//],],;

After successful registration there will be data in database generation check Database

ID  name    email   password    remember_token  created_at  updated_at1   123456  1239@ Qq.com $2Y$10$EFEO1GCCK6JDWGXJQJNBK.FVZJGU7I68UKMPQNWBX9VPNVUVGTHM6    Wsar4v256k4xxisbbivns1o9ieqwcaidzb5nk5yzyj5jnbeniiowtalrbnnt    2016-05-25 15:31:07 2016-05-25 15:41:53

Each login success will have a laravel_session, and guard is to check this thing, to determine whether to login and so on.

  • 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.