Home >PHP Framework >Laravel >Detailed explanation of Laravel registration refactoring

Detailed explanation of Laravel registration refactoring

藏色散人
藏色散人forward
2020-11-18 15:15:211994browse

The following is an introduction to Laravel registration reconstruction from the Laravel framework tutorial column. I hope it will be helpful to friends who need it!

Detailed explanation of Laravel registration refactoring

You need to use laravel to build a backend content management system, but laravel’s default login registration cannot meet the current needs
If you register, because it is used in the backend, There is no need to register using an email address, and there will be some additional configurations that need to be filled in during registration.

1. First determine the route for user registration

When we install laravel, the registration generated by default is registered by email, and some options are not required, and some are required. Add some form options
If we register, we cannot register casually. Only some super administrators can register.
First we use the last created UserController for configuration. If not, You can use php artisan make:controller UserController to create a controller class
and then create two routesRoute::get('register', 'UserController@getRegister')andRoute::post('register', 'UserController@postRegister')
The former is a get request to display a registered page, followed by a post request to register an account.

2. Display the registered account page

This uses the getRegister method. This method only needs to display a view so there is no special logic

    public function getRegister()
    {
        return view('auth.register');
    }

3. Request to register an account

This uses postRegisterThis method
Registering an account is the same as resetting a password, and it is more convenient than registering an account Simpler.
When we insert a user record into the database, we can use User::create($data) to insert.
$data is an array that stores the key and value of each field

    public function postRegister(Request $request)
    {
        $rules = [
            'username'=>'required|unique:finance_enewsuser',
            'password' => 'required|between:6,20|confirmed'
        ];
        $messages = [
            'required'=>':attribute不能为空',
            'unique'=>'用户名已被注册',
            'between' => '密码必须是6~20位之间',
            'confirmed' => '新密码和确认密码不匹配'
        ];
        $username = $request->input('username');
        $password = $request->input('password');
        $group = $request->input('group');
        $data = $request->all();
        $validator = Validator::make($data, $rules, $messages);
        if ($validator->fails()) {
            return back()->withErrors($validator);
        }
        $data = [
            'username' => $username,
            'password' => bcrypt($password),
            'groupid' => $group,
            'checked' => 0,
            'styleid' => 1,
            'filelevel' => 0,
            'loginnum' => 0,
            'lasttime' => time(),
            'lastip' => '127.0.0.1',
            'truename' => '',
            'email' => '',
            'pretime' => time(),
            'preip' => '127.0.0.1',
        ];
        User::create($data); //插入一条新纪录,并返回保存后的模型实例
        //如果注册后还想立即登录的话,可以使用$user = User::create($data); Auth::login($user); 进行认证
        return redirect('/');
    }

4. Completed example

UserController

    public function getRegister()
    {
        return view('auth.register');
    }

    public function postRegister(Request $request)
    {
        $rules = [
            'username'=>'required|unique:finance_enewsuser',
            'password' => 'required|between:6,20|confirmed'
        ];
        $messages = [
            'required'=>':attribute不能为空',
            'unique'=>'用户名已被注册',
            'between' => '密码必须是6~20位之间',
            'confirmed' => '新密码和确认密码不匹配'
        ];
        $username = $request->input('username');
        $password = $request->input('password');
        $group = $request->input('group');
        $data = $request->all();
        $validator = Validator::make($data, $rules, $messages);
        if ($validator->fails()) {
            return back()->withErrors($validator);
        }
        $data = [
                    'username' => $username,
                    'password' => bcrypt($password),
                    'groupid' => $group,
                    'checked' => 0,
                    'styleid' => 1,
                    'filelevel' => 0,
                    'loginnum' => 0,
                    'lasttime' => time(),
                    'lastip' => '127.0.0.1',
                    'truename' => '',
                    'email' => '',
                    'pretime' => time(),
                    'preip' => '127.0.0.1',
                ];
        User::create($data); //插入一条新纪录,并返回保存后的模型实例
        return redirect('/');
    }

register.blade

    <form class="login-form" action="{{ url(&#39;/register&#39;) }}" method="post">
        {!! csrf_field() !!}
        <h3 class="font-green">Sign Up</h3>
        @if(count($errors) > 0)
            <p class="alert alert-danger display-hide" style="display: block;">
                <button class="close" data-close="alert"></button>
                <span> {{ $errors->first() }}  </span>
            </p>
        @endif
        <p class="form-group">
            <label class="control-label visible-ie8 visible-ie9">用户名</label>
            <input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username"> </p>
        <p class="form-group">
            <label class="control-label visible-ie8 visible-ie9">密码</label>
            <input class="form-control placeholder-no-fix" type="password" autocomplete="off" id="register_password" placeholder="Password" name="password"> </p>
        <p class="form-group">
            <label class="control-label visible-ie8 visible-ie9">重复密码</label>
            <input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Repeat password" name="password_confirmation"> </p>
        <p class="form-group">
            <label class="control-label visible-ie8 visible-ie9">用户组</label>
            <select name="group" class="form-control">
                    <option value="1"> 超级管理员 </option>
                    <option value="2"> 管理员 </option>
                    <option value="3"> 编辑 </option>
            </select>
        </p>
        <p class="form-actions">
            <button type="submit" id="register-submit-btn" class="btn btn-success uppercase pull-right">注册</button>
        </p>
    </form>

5. Middleware--Users must log in

Now that the registration is complete, we only need the user's judgment.
Required account registration must only be an account with super administrator privileges.
In this case, our general procedure is to directly check the user's information in the postRegister method, and then check whether the user meets this permission. If not, jump to other pages.
This method is okay, but since we have the permissions of super administrator and administrator, it must be used in more than one place, and it will also be used in other places.
Then someone will think of writing a method in the model, which can be called directly if needed in the future.
This method is also possible, but we recommend using the middleware function provided by laravel. This function is very powerful and easy to use. Now we will use the middleware function.
Because we are a backend content management system, we first create a middleware. The function is that all pages must be logged in before entering, otherwise they will jump to the login page.
Check the manual and find that you can use the php artisan make:middleware CheckLoginMiddleware command to create a middleware. Of course, copy a similar file and change it the same way.
Then a CheckLoginMiddleware middleware file will be created in the app/Http/Middleware/ directory, which has only one handle() method, we directly Add our function inside

    <?php

    namespace App\Http\Middleware;

    use Closure;
    use Auth;

    class CheckLoginMiddleware
    {
        public function handle($request, Closure $next)
        {
            //使用Auth方法,需要引入use Auth;方法
            //$request->is('login')表示请求的URL是否是登录页
            //因为我们打算使用全局的,所以,需要把登录页排除,不然会无限重定向
            //如果你的登录页不是/login,而是/auth/login的话,就写$request->is('auth/login')
            //并且我们要在请求处理后执行其任务,因为我们需要获取到用户的登录信息
            $response = $next($request);
            if (!Auth::check() && !$request->is('login')) {
                return redirect('/login');
            }
            return $response;
        }
    }

The function of this middleware is that if a route is generated, first use Auth::check() to determine whether the user is logged in. If there is no login jump, Go to the login page.
The method is written, but it cannot be used yet. We need to register this middleware and tell the framework that the middleware is written and can be used, and what is the scope of use.
There is a Kernel.php file in the app/Http/ directory to register this middleware, which means to tell the framework that we have written this middleware.
There are two array attributes in the Kernel.php file, one $middleware means global use, and the other $routeMiddleware means it can be used selectively.
Global use means that no matter which page you request, this middleware will be executed first.
Choose to use to indicate which HTTP request is required and where the middleware is required to be executed.
If every page here requires login, you can register a global one. Add a

\App\Http\Middleware\CheckLoginMiddleware::class

to the $middleware

array attribute and register it. Used

PS: Please remember that if you define a global one, be extra careful. For example, above we have to exclude the login page, otherwise because the user is not logged in, every page will be redirected to Login page, including login page

5. 中间件--特殊页面需要验证用户组

现在是进行用户权限页面的限制,同样我们也要重新创建一个中间件
使用php artisan make:middleware CheckGroupMiddleware创建一个新的中间件,用来判断这个用户是否满足这个权限

    <?php

    namespace App\Http\Middleware;

    use Closure;
    use Auth;

    class CheckGroupMiddleware
    {
        public function handle($request, Closure $next)
        {
            $user = Auth::user();
            if ($user->groupid != 1) {
                return redirect('/');
            }
            return $next($request);
        }
    }

这里我们还是通过Auth::user()来获取到用户的信息,然后判断用户的组,不属于超级管理员就跳到首页。
然后我们在到app/Http/目录下有个Kernel.php文件是注册这个中间件的,这次我们注册为可以选择的中间件。
这个中间件因为是可以选择的,所以我们还需要给它起个别名,在$routeMiddleware数组属性里加如一条

    'user.group' => \App\Http\Middleware\CheckGroupMiddleware::class

创建一个可以使用usergroup这个名字使用的中间件。
创建好后,我们可以选择在哪里使用,一个是在router.php的路由文件里加入,一个是在controller里使用
router.php文件里使用

    Route::get('/', ['middleware' => ['user.group'], function () {
        //
    }]);

在控制器内使用

    $this->middleware('user.group');

这里我们选择在路由里添加中间件。让注册页面只能是超级管理员才可以注册

    Route::get('register', 'UserController@getRegister')->middleware('user.group');
    Route::post('register', 'UserController@postRegister')->middleware('user.group');

我们目前只有两个路由要判断权限,所以使用了链式的写法,当然你也可以按照手册里上使用组的方式,组的方式更为优雅。

当然如果你的整个控制器内的方法都需要中间件进行验证过滤的话,你也可以创建组的形式,也可以直接在控制器内使用__construct方法,让每次请求这个控制器时,先执行中间件

    class MyController extends Controller
    {
        public function __construct()
        {
            $this->middleware('user.group');
        }

        public function index()
        {
            return view('my.index');
        }
    }

The above is the detailed content of Detailed explanation of Laravel registration refactoring. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete