Table of Contents
1. First determine the route for user registration
2. Display the registered account page
3. Request to register an account
4. Completed example
5. Middleware--Users must log in
5. 中间件--特殊页面需要验证用户组
Home PHP Framework Laravel Detailed explanation of Laravel registration refactoring

Detailed explanation of Laravel registration refactoring

Nov 18, 2020 pm 03:15 PM
laravel

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');
    }
Copy after login

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('/');
    }
Copy after login

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('/');
    }
Copy after login

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>
Copy after login

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;
        }
    }
Copy after login

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
Copy after login

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);
        }
    }
Copy after login

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

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

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

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

在控制器内使用

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

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

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

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

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

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

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

Laravel and the Backend: Powering Web Application Logic Laravel and the Backend: Powering Web Application Logic Apr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

Laravel's geospatial: Optimization of interactive maps and large amounts of data Laravel's geospatial: Optimization of interactive maps and large amounts of data Apr 08, 2025 pm 12:24 PM

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

See all articles