Implementation method of data validation and user authentication in laravle5.4

小云云
Release: 2023-03-21 14:08:02
Original
1112 people have browsed it


This article mainly shares with you the implementation methods of laravle5.4 data verification and user authentication, hoping to help everyone.

1. Planning routing

//登入模块
Route::match(['get','post'],'/admin/login','Admin\ManagerController@login');
Copy after login

2. Generating controller

php artisan make:controller Admin\ManagerController
Copy after login

3. Writing methods corresponding to the controller

public function Login(Request $request){    if($request->isMethod('get')){        //显示视图
        return view('Admin.login');
    }elseif($request->isMethod(''post)){        //数据处理
        //1.数据验证(用户名长度是否合法)
        //2.用户认证(用户名和密码在数据库中是否存在)
    }
}
Copy after login

Integrated verification code class

1. Install the verification code function package

Function package address: Verification code function package
Use command:

composer require mews/captcha
Copy after login

Instructions: If an error occurs, check whether the PHP extension php_fileinfo is turned on

2. Register the verification code function package into laravel

2.1 Modify config/app.php and add the following code in the providers item:

//集成验证码类
    Mews\Captcha\CaptchaServiceProvider::class,
Copy after login

2.2 Register an alias

Modify the aliases array:
Remove the alias of the integrated verification code class, and you can use the facade Captcha like Route in the future
Add the following code:

'Captcha' => Mews\Captcha\Facades\Captcha::class,
Copy after login

Description: This verification code Classes can also be configured

① Execute the command:
php artisan vendor:publish
Copy after login
② After executing the command, the file config/captcha.php
will be generated ③ Configuration, such as:
return [
    'default'   => [
        'length'    => 5,
        'width'     => 120,
        'height'    => 36,
        'quality'   => 90,
    ],
    // ...
];
Copy after login

3. Generate verification code class:

There are two methods to generate:

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

  2. In the controller: Captcha::src(); visible: blog post

3.1 Generate directly in the view

                <img  src="{{ captcha_src() }}" alt="Implementation method of data validation and user authentication in laravle5.4" > <a id="kanbuq" href="javascript:;">看不清,换一张</a> </p>
Copy after login

4. Data Verification

4.1 The first method

 public function login(Request $request)
{
    if($request->isMethod(&#39;get&#39;)){
        //显示数据
        return view(&#39;Admin.login&#39;);
    }elseif($request->isMethod(&#39;post&#39;)){
        //数据处理
        //1.数据验证(用户名长度,是否为空)
        /*
         *参数一:$request对象【接收的数据】
         * 参数二:验证规则
         * */
        //第一种方式:
           $this->validate($request,[
           &#39;username&#39;=>&#39;required|min:2|max:16&#39;,
            &#39;password&#39;=>&#39;required|between:4,20&#39;,
            &#39;captcha&#39;=>&#39;required|size:5|captcha&#39;,//这里的captcha规则是继承的验证码插件自带的
        ]);
        echo "验证通过";
            }
}
Copy after login

4.2, the second method: Use validator facade verification

First you need to introduce the class:

use Validator;

 public function login(Request $request)
    {
        if($request->isMethod(&#39;get&#39;)){
            //显示数据
            return view(&#39;Admin.login&#39;);
        }elseif($request->isMethod(&#39;post&#39;)){
            //数据处理
            //1.数据验证(用户名长度,是否为空)
            /*
             *参数一:$request对象【接收的数据】
             * 参数二:验证规则
             * */
           //第二种方式:
            $validator = Validator::make($request->all(),[
               &#39;username&#39;=>&#39;required|min:2|max:16&#39;,
                &#39;password&#39;=>&#39;required|between:4,20&#39;,
                &#39;captcha&#39;=>&#39;required|size:5|captcha&#39;,
            ]);
            if($validator->fails()){
                return redirect(&#39;/admin/login&#39;)//验证失败后跳转地址
                        ->withErrors($validator)//将错误信息一次性保存到session中
                        ->withInput();//保留原来输入的值
            }
            echo "验证通过";
                    }
    }
Copy after login

In the template Display error message:

@if (count($errors) > 0)        <p class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)                    <li>{{ $error }}</li>
                @endforeach            </ul>
        </p>
    @endif
Copy after login

**Note: Because the withErrors() function saves the error message to the session at one time, if you want to retain the value in the input box after verifying the error, you can use old( )Function
such as:

<input id="username" name="username" value="{{ old(&#39;username&#39;) }}" type="text" placeholder="账户" class="input-text size-L">
Copy after login

5. About the error message displayed in English

The error message displayed by laravel by default is in English. If we want to display it in Chinese, we need Download the language pack, address: Chinese language pack

5.1. After unzipping, copy zh-CN in the language pack to the resources/lang directory

5.2. Modify the local of config/app.php Attribute, ensure to be consistent with the file name in the lang directory

&#39;locale&#39; => &#39;zh-CN&#39;
Copy after login

5.3. Customize to add captcha translation

Because by default, there is no Chinese translation corresponding to captcha in the language package, we can customize it , add

 &#39;captcha&#39;               =>&#39;验证码&#39;,
Copy after login
5.4, add the translation of validation.captcha

# in the array

attributes

option in the resources/lang/zh-CN/validation.php file ##Judge whether the verification code is correct
You need to add captcha to the verification rules, which are rules provided by third-party plug-ins
Implementation method of data validation and user authentication in laravle5.4Modify the file as follows:

Implementation method of data validation and user authentication in laravle5.4

User Authentication

1.Introducing the Auth facade

//引入auth门面,用户认证
use Illuminate\Support\Facades\Auth;
Copy after login

2Writing method

Add the following code in the login method

public function login(Request $request)
    {
        if($request->isMethod(&#39;get&#39;)){            //显示数据
            return view(&#39;Admin.login&#39;);
        }elseif($request->isMethod(&#39;post&#39;)){            //数据处理
            //1.数据验证(用户名长度,是否为空)
            /*
             *参数一:$request对象【接收的数据】
             * 参数二:验证规则
             * */

           //第二种方式:
            $validator = Validator::make($request->all(),[               &#39;username&#39;=>&#39;required|min:2|max:16&#39;,                &#39;password&#39;=>&#39;required|between:4,20&#39;,                &#39;captcha&#39;=>&#39;required|size:5|captcha&#39;,
            ]);            if($validator->fails()){                return redirect(&#39;/admin/login&#39;)
                        ->withErrors($validator)//将错误信息一次性保存到session中
                        ->withInput();//保留原来输入的值
            }            //2.用户认证(用户名与密码在数据库中是否能查询到)
            $username  =$request->input(&#39;username&#39;);            $password = $request->input(&#39;password&#39;);            if(Auth::guard(&#39;admin&#39;)->attempt([&#39;username&#39;=>$username,&#39;password&#39;=>$password])){                echo "认证成功";                //记录认证状态
            }else{                echo "认证失败";                //跳转到登入页面
            }

        }
    }
Copy after login

Found error:


Implementation method of data validation and user authentication in laravle5.4

Cause: SQL query is the it_users table
Solution: Modify auth configuration

1. Customize guard configuration

    &#39;guards&#39; => [        &#39;web&#39; => [          
      &#39;driver&#39; => &#39;session&#39;,            &#39;provider&#39; => &#39;users&#39;,
        ],        &#39;api&#39; => [            &#39;driver&#39; => &#39;token&#39;,           
         &#39;provider&#39; => &#39;users&#39;,
        ],        &#39;admin&#39; =>[            &#39;driver&#39; => &#39;session&#39;,          
          &#39;provider&#39; => &#39;admin&#39;,
          //报错信息,我们加入这样一个数组,对应下面的provider的配置
        ],
    ],
Copy after login

2. Configure providers

    &#39;providers&#39; => [        &#39;users&#39; => [           
     &#39;driver&#39; => &#39;eloquent&#39;,            &#39;model&#39; => App\User::class,
        ],        &#39;admin&#39; => [            
        &#39;driver&#39; => &#39;eloquent&#39;,           
         &#39;model&#39; => App\Manager::class,//建立的模型是与这里的Manager名称一致
        ],      
          // &#39;users&#39; => [       
           //     &#39;driver&#39; => &#39;database&#39;,      
             //     &#39;table&#39; => &#39;users&#39;,        // ],
    ],
Copy after login

3. Modify the login method in ManagerController.php

 public function login(Request $request)
    {
        if($request->isMethod(&#39;get&#39;)){            //显示数据
            return view(&#39;Admin.login&#39;);
        }elseif($request->isMethod(&#39;post&#39;)){            //数据处理
            //1.数据验证(用户名长度,是否为空)
            /*
             *参数一:$request对象【接收的数据】
             * 参数二:验证规则
             * */
            //第一种方式:
           /* $this->validate($request,[
               &#39;username&#39;=>&#39;required|min:2|max:16&#39;,
                &#39;password&#39;=>&#39;required|between:4,20&#39;,
                &#39;captcha&#39;=>&#39;required|size:5|captcha&#39;,//这里的captcha规则是继承的验证码插件自带的
            ]);*/
           //第二种方式:
            $validator = Validator::make($request->all(),[               &#39;username&#39;=>&#39;required|min:2|max:16&#39;,                &#39;password&#39;=>&#39;required|between:4,20&#39;,                &#39;captcha&#39;=>&#39;required|size:5|captcha&#39;,
            ]);            if($validator->fails()){                return redirect(&#39;/admin/login&#39;)
                        ->withErrors($validator)//将错误信息一次性保存到session中
                        ->withInput();//保留原来输入的值
            }            //2.用户认证(用户名与密码在数据库中是否能查询到)
            $username  =$request->input(&#39;username&#39;);            $password = $request->input(&#39;password&#39;);            //使用自定义的guard【admin】
            if(Auth::guard(&#39;admin&#39;)->attempt([&#39;username&#39;=>$username,&#39;password&#39;=>$password])){               return redirect(&#39;/admin/index&#39;);                //记录认证状态
            }else{                echo "认证失败";                //跳转到登入页面
                return redirect(&#39;/admin/login&#39;)
                    ->withErrors([&#39;loginError&#39;=>&#39;用户名或密码错误&#39;])
                    ->withInput();
            }

        }
    }
Copy after login

Create Manager model

Execute command:

php artisan make:model Manager
Copy after login

Write Manager.php model

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Manager extends Model{

    //3.定义属性:代表软删除的字段
    protected $data = [&#39;deleted_at&#39;];    protected $table = "manager";    protected  $primaryKey = "mg_id";    protected $fillable = [&#39;username&#39;,&#39;password&#39;,&#39;mg_role_ids&#39;,&#39;mg_sex&#39;,&#39;mg_phone&#39;,&#39;mg_email&#39;,&#39;mg_remark&#39;];
}
Copy after login

Found an error


Implementation method of data validation and user authentication in laravle5.4

Solution:

Implement the Auth interface in the model (Contract) Introducing the interface:

use \Illuminate\Auth\Authenticatable;
Copy after login

Use the use keyword inside the class: contains trait, implements the contract

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Manager extends Model implements \Illuminate\Contracts\Auth\Authenticatable{
    //使用auth模块下的Authenticatable实现Contracts\Auththenticatable
    //查看这个类,发现这个类是trait 类型,就可以在类内使用use + 类名,从而可以使用这个类的方法
    use \Illuminate\Auth\Authenticatable;    //3.定义属性:代表软删除的字段
    protected $data = [&#39;deleted_at&#39;];    protected $table = "manager";    protected  $primaryKey = "mg_id";    protected $fillable = [&#39;username&#39;,&#39;password&#39;,&#39;mg_role_ids&#39;,&#39;mg_sex&#39;,&#39;mg_phone&#39;,&#39;mg_email&#39;,&#39;mg_remark&#39;];
}
Copy after login
Note:

Note: If in After successful authentication, the verification code cannot be displayed normally when returning to the login page. Delete the session file under storage\framework\sessions

Related recommendations:

Instance analysis of php implementing various data verification

php form data verification class, php form verification_PHP tutorial

PHP code implements form data validation class_php example

The above is the detailed content of Implementation method of data validation and user authentication in laravle5.4. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!