Implementation of laravle5.4 data authentication and user authentication

Source: Internet
Author: User
Tags class manager php form php form validation


This article is mainly to share with you laravle5.4 data validation and user authentication implementation method, hope to help everyone.

1. Planning for routing

Login Module Route::match ([' Get ', ' post '], '/admin/login ', ' admin\managercontroller@login ');

2. Build controller

PHP Artisan Make:controller Admin\managercontroller

3, write the controller corresponding method

Public Function Login (Request $request) {    if ($request->ismethod (' get ')) {        //Display view        return (' Admin.login ');    } ElseIf ($request->ismethod ("Post)) {        //Data processing        //1. Data validation (user name length is legal)        //2. User authentication (user name and password exist in database)    }}

Integrated Verification Code class

1. Install the Verification Code Feature Pack

Feature Pack Address: Verification Code Feature Pack
Use the command:

Composer require Mews/captcha

Note: If an error occurs, check to see if PHP extension Php_fileinfo is turned on

2. Register the Verification Code feature pack with the Laravel

2.1 Modify config/app.php, add the following code to the providers entry:

Integrated verification Code class    Mews\captcha\captchaserviceprovider::class,

2.2 Registering aliases

To modify an aliases array:
Add the integrated Captcha class to the individual name, and you can use the façade captcha like a route later
Add the following code:

' Captcha ' = Mews\captcha\facades\captcha::class,

Description: The Captcha class can also be configured

① Execute Command:

PHP Artisan Vendor:publish

② a file is generated when the command finishes executing config/captcha.php

③ configuration, such as:

return [    ' default '   = + [        ' length '    = 5,        ' width ' = ' + ',        ' height '    = 36,        ' quality '   = +,    ],    //...];

3. Generate Verification Code class:

There are two ways to generate:

    1. In the View: Captcha::create ();

    2. In the controller: CAPTCHA::SRC (); Visible: blog post

3.1 Generating directly in the view

                 <a id= "kanbuq" href= "javascript:;" > can not see Clearly, change a </a> </p>

4. Data validation

4.1 The first one

Public Function Login (Request $request) {    if ($request->ismethod (' get ')) {        //Display Data        return view (' Admin.login ');    } ElseIf ($request->ismethod (' post ')) {        //Data processing        //1. Data validation (user name length, whether blank)        /         * * Parameter one: $request object "Data Received"         * Parameter two: validation rules         * *        ///First way:           $this->validate ($request, [           ' username ' = ' required|min:2| ') Max:16 ',            ' password ' = ' required|between:4,20 ',            ' captcha ' = ' required|size:5|captcha ',// The captcha rule here is inherited code plugin comes with        ]);        echo "Validation passed";            }}

4.2, the second way: using validator façade verification

First you need to introduce a class:

Use Validator; Public Function Login (Request $request)    {        if ($request->ismethod (' get ')) {            //Display Data            return view (' Admin.login ');        } ElseIf ($request->ismethod (' post ')) {            //Data processing            //1. Data validation (user name length, whether blank)            /             * * Parameter one: $request object "Data Received"             * Parameter two: verification Rule             * *           ///Second way:            $validator = Validator::make ($request->all (), [               ' username ' = > ' required|min:2|max:16 ',                ' password ' = ' required|between:4,20 ',                ' captcha ' = ' required|size:5| ' Captcha ',            ]);            if ($validator->fails ()) {                return redirect ('/admin/login ')//verify failed after jump address                        ->witherrors ($validator)// Save the error message to the session                        ->withinput ();//Keep the original input value            }            echo "validation passed";                    }    }

To display an error message in the template:

@if (Count ($errors) > 0)        <p class= "alert Alert-danger" >            <ul>                @foreach ($errors->all () As $error)                    <li>{{$error}}</li>                @endforeach            </ul>        </p>    @endif

* * Note: Because the witherrors () function saves the error message to the session once, if you want the value in the input box to remain after the validation error, you can use the old () function
Such as:

<input id= "username" name= "username" value= "{{old (' username ')}}" type= "text" placeholder= "account" class= "Input-text Size-l ">

5, about the error message display in English

Laravel the error message displayed by default is English, we need to download the language pack if we want to display it in Chinese, address: Chinese language pack

5.1. After decompression, copy the ZH-CN in the language pack to the Resources/lang directory

5.2. Modify the local property of the config/app.php to ensure that the file name is consistent with the Lang directory

' Locale ' = ' ZH-CN '

5.3. Custom Add CAPTCHA Translation

Because, by default, the language pack does not have a captcha corresponding to the Chinese translation, we can customize the array attributes options in the resources/lang/zh-cn/validation.php file to add

' captcha '               = ' Verification Code ',

5.4. Add Validation.captcha Translation

determine if the verification code is correct
need to include CAPTCHA in validation rules, which are rules provided by third-party plug-ins

Modify the file as follows:

User authentication

1. Introduction of Auth Façade

Introduction of Auth façade, user authentication use Illuminate\support\facades\auth;

2 Writing methods

Add the following code to the login method

Public Function Login (Request $request) {if ($request->ismethod (' get ')) {//Display data return        View (' Admin.login '); }elseif ($request->ismethod (' post ')) {//Data processing//1. Data validation (user name length, whether blank)/* * Parameter one: $ Request Object "Data received" * parameter two: validation rule * *///second way: $validator = Validator::make ($reque St->all (), [' username ' = ' required|min:2|max:16 ', ' password ' = ' required|between:4,20 '            , ' captcha ' = ' Required|size:5|captcha ',]); if ($validator->fails ()) {return redirect ('/admin/login ')->witherrors ($validat OR)//To save the error message to the session->withinput ();//Keep the original input value}//2. user authentication (user name and password in database            can be queried) $username = $request->input (' username ');            $password = $request->input (' password '); if (Auth::guard (' admin ')->aTtempt ([' username ' + $username, ' password ' + $password])) {echo "Certified successful";                Record authentication status}else{echo "Authentication failed"; Jump to login page}}}

Error found:

cause: The SQL query is a it_users table
FIX: Modify AUTH configuration

1. Custom Guard Configuration

    ' Guards ' = [        ' web ' + = '                driver ' + ' session ',            ' provider ' and ' users ',        ],        ' API ' = [ c8/> ' driver ' = ' token ', ' provider ' and ' users ', ',        ' admin ' =>[            ' driver ' and ' session ', c13/> ' provider ' = ' admin ',          //error message, we add such an array, corresponding to the following provider configuration        ],    

2. Configure providers

    ' Providers ' = [        ' users ' and ' = '                driver ' = ' eloquent ',            ' model ' + App\user::class,        ],        ' Admin ' = ' = [                    ' driver ' = ' eloquent ',                    ' model ' and ' app\manager::class,//' are built with the same Manager name as here        ],                //' users ' + = [                  //     ' driver ' + ' database ',                   //     ' table ' = ' users ',        //]    ,

3. Modify the login method in managercontroller.php

 Public Function Login (Request $request) {if ($request->ismethod (' get ')) {//Display data return        View (' Admin.login '); }elseif ($request->ismethod (' post ')) {//Data processing//1. Data validation (user name length, whether blank)/* * Parameter one: $               Request Object "Data received" * parameter two: validation rule * *////First way:/* $this->validate ($request, [                ' Username ' = ' required|min:2|max:16 ', ' password ' = ' required|between:4,20 ', ' Captcha ' = ' required|size:5|captcha ',///Here the CAPTCHA rule is inherited code plugin comes with]); *///Second way: $validat or = Validator::make ($request->all (), [' username ' = ' required|min:2|max:16 ', ' password ' =            > ' required|between:4,20 ', ' captcha ' = ' Required|size:5|captcha ',]); if ($validator->fails ()) {return redirect ('/admin/login ')->witherrors ($validat OR)//WillThe error message is saved to the session->withinput ();//Keep the value originally entered}//2. user authentication (user name and password can be queried in the database)            $username = $request->input (' username ');            $password = $request->input (' password ');                Use the Custom Guard "admin" if (auth::guard (' admin ')->attempt ([' username ' = = $username, ' password ' = ' = $password])) {                Return redirect ('/admin/index ');                Record authentication status}else{echo "Authentication failed";                     Jump to login page return redirect ('/admin/login ')->witherrors ([' loginError ' = ' username or password error '])            ->withinput (); }        }    }

Creating the manager model

Execute command:

PHP Artisan Make:model Manager

Writing the manager.php model

<?phpnamespace app;use illuminate\database\eloquent\model;class Manager extends model{    //3. Defining properties: Fields that represent soft deletions    protected $data = [' deleted_at '];    Protected $table = "Manager";    protected  $primaryKey = "mg_id";    protected $fillable = [' username ', ' password ', ' mg_role_ids ', ' mg_sex ', ' mg_phone ', ' mg_email ', ' Mg_remark '];}

Found an error

Workaround: Implement the Auth Interface (contract) in the model
Introduction Interface:

Use \illuminate\auth\authenticatable;

Using the Use keyword inside a class: Contains trait, implements the contract

<?phpnamespace app;use Illuminate\database\eloquent\model;class Manager extends Model implements \illuminate\ contracts\auth\authenticatable{    //Use the authenticatable implementation under the Auth module contracts\auththenticatable    //view this class, It is found that this class is a trait type and can be used within a class using the Use + class name, so that the class can be used using the    \illuminate\auth\authenticatable method.    3. Define properties: Represents a soft-deleted field    protected $data = [' deleted_at '];    Protected $table = "Manager";    protected  $primaryKey = "mg_id";    protected $fillable = [' username ', ' password ', ' mg_role_ids ', ' mg_sex ', ' mg_phone ', ' mg_email ', ' Mg_remark '];}

Note: If after the successful authentication, the return login page verification code can not be normal storage\framework\sessions under the session file deletion

Related recommendations:

Example Analysis of PHP implementation of data validation

PHP form data validation class, PHP form validation _php Tutorial

PHP Code implementation form data validation class _php instance

Related Article

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.