search
HomePHP FrameworkLaravelDetailed explanation of Laravel registration refactoring

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

    
        {!! csrf_field() !!}         

Sign Up

        @if(count($errors) > 0)             

                                  {{ $errors->first() }}               

        @endif         

                          

        

                          

        

                          

        

                                  

        

                     

    

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. If there is any infringement, please contact admin@php.cn delete
Mastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMay 08, 2025 am 12:25 AM

Laravelsoftdeletesallow"deletion"withoutremovingrecordsfromthedatabase.Toimplement:1)UsetheSoftDeletestraitinyourmodel.2)UsewithTrashed()toincludesoft-deletedrecordsinqueries.3)CreatecustomscopeslikeonlyTrashed()forstreamlinedcode.4)Impleme

Laravel Soft Deletes: Restoring and Permanently Deleting RecordsLaravel Soft Deletes: Restoring and Permanently Deleting RecordsMay 08, 2025 am 12:24 AM

In Laravel, restore the soft deleted records using the restore() method, and permanently delete the forceDelete() method. 1) Use withTrashed()->find()->restore() to restore a single record, and use onlyTrashed()->restore() to restore a single record. 2) Permanently delete a single record using withTrashed()->find()->forceDelete(), and multiple records use onlyTrashed()->forceDelete().

The Current Laravel Release: Download and Upgrade Today!The Current Laravel Release: Download and Upgrade Today!May 08, 2025 am 12:22 AM

You should download and upgrade to the latest Laravel version as it provides enhanced EloquentORM capabilities and new routing features, which can improve application efficiency and security. To upgrade, follow these steps: 1. Back up the current application, 2. Update the composer.json file to the latest version, 3. Run the update command. While some common problems may be encountered, such as discarded functions and package compatibility, these issues can be solved through reference documentation and community support.

Laravel: When should I update to the last version?Laravel: When should I update to the last version?May 08, 2025 am 12:18 AM

YoushouldupdatetothelatestLaravelversionwhenthebenefitsclearlyoutweighthecosts.1)Newfeaturesandimprovementscanenhanceyourapplication.2)Securityupdatesarecrucialifvulnerabilitiesareaddressed.3)Performancegainsmayjustifyanupdateifyourappstruggles.4)Ens

Laravel Soft Delete: How to Prevent Permanent Data LossLaravel Soft Delete: How to Prevent Permanent Data LossMay 08, 2025 am 12:04 AM

Laravel'ssoftdeletefeaturecanbeusedeffectivelytosafeguarddatabyfollowingspecificstepsandbestpractices.1)ImplementsoftdeletesusingtheSoftDeletestraitinyourmodel.2)UsewithTrashed()toquerysoft-deletedrecordsforauditingorrecovery.3)UseforceDelete()cautio

Laravel Version Tracker: Always Know the Latest ReleaseLaravel Version Tracker: Always Know the Latest ReleaseMay 07, 2025 pm 06:25 PM

Developers can efficiently track new versions of Laravel and ensure the use of the latest and safest code bases: 1. Use code snippets to check the latest version and compare it with the current version, 2. Use Composer and Laravel for dependency management, 3. Implement automated testing to deal with version conflicts, 4. Get feedback on new versions through community interaction, 5. Pay attention to Laravel's public roadmap and GitHub dynamics to plan updates.

Laravel Lastest version: Security updatesLaravel Lastest version: Security updatesMay 07, 2025 pm 05:25 PM

Laravel's latest version (9.x) brings important security updates, including: 1) patching known vulnerabilities such as CSRF attacks; 2) enhancing overall security, such as CSRF protection and SQL injection defense. By understanding and applying these updates correctly, you can ensure that your Laravel app is always in the safest state.

The Ultimate Guide to Laravel Migrations: Database Structure ManagementThe Ultimate Guide to Laravel Migrations: Database Structure ManagementMay 07, 2025 pm 05:05 PM

LaravelMigrationsareversioncontrolfordatabases,allowingschemamanagementandevolution.1)Theyhelpmaintainteamsyncandconsistencyacrossenvironments.2)Usethemtocreatetableslikethe'users'tablewithnecessaryfields.3)Modifyexistingtablesbyaddingfieldslike'phon

See all articles

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.