On the analysis of Laravel registration reconfiguration

Source: Internet
Author: User
Tags button type
This article mainly introduces the Laravel registration reconstruction of the analysis, has a certain reference value, now share to everyone, the need for friends can refer to

Sometimes need to use laravel to build a back-end content management system, but laravel default login registration can not meet the current requirements, so this requires laravel registration refactoring, followed by a small series to see how to perform the registration reconstruction.

1. First determine the user-registered route

When we install the Laravel, the default generated registrations are registered with the mailbox, and some options are not required, some require some form options

If we register, it is not easy to register, only some Super administrator can register

First we use the configuration we created last UserController , and if not, we can use to php artisan make:controller UserController create a controller class

Then create two routes Route::get('register', 'UserController@getRegister') andRoute::post('register', 'UserController@postRegister')

The former is a request to display a registered page get , followed by a request to register an account post .

2. Display the Registered Account page

This method is used getRegister , this method only needs to display a view, so there is no special logic

Public Function Getregister () {return view (' Auth.register ');}

3. Request a registered Account

This is how this is used. postRegister

Registering an account is the same as resetting the password, and is simpler than registering an account.

When we insert a user record into the database, we can use it User::create($data) to insert it.

$datais the array, which holds the keys and values for each field

Public Function Postregister (Request $request) {$rules = [' username ' = ' required|unique:finance_enewsuser ', ' Password ' = ' required|between:6,20|confirmed ']; $messages = [' Required ' = ': attribute cannot be null ', ' unique ' = ' username ' has been registered ', ' between ' + ' password must be between 6~20 bits ', ' confirmed ' =&G T ' New password and confirmation password do not match ']; $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, ' Passwo Rd ' + bcrypt ($password), ' groupid ' = $group, ' checked ' + 0, ' styleid ' and ' = 1, ' Filelevel ' + 0, ' Logi Nnum ' + 0, ' lasttime ' + Time (), ' lastip ' = ' 127.0.0.1 ', ' truename ' + ' ', ' email ' = ', ' pretime ' = Time (), ' preip ' = ' 127.0.0.1 ',]; User::create ($data); Insert a new record and return to the saved model instance//If you want to log in immediately after registering, you can use $user = User::create ($data); Auth::login ($user); to certify return redirect ('/');}

4. After the completion of the 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 cannot be null ', ' unique ' = ' username ' has been registered ', ' between ' + ' password must be between 6~20 bits ', ' confirmed ' =&G T ' New password and confirmation password do not match ']; $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, ' PA ssWOrd ' + bcrypt ($password), ' GroupID ' + $group, ' checked ' + 0, ' styleid ' = 1, ' Filelevel ' =&G T 0, ' Loginnum ' + 0, ' lasttime ' + Time (), ' lastip ' = ' 127.0.0.1 ', ' truename ' = ', ' email ' =& Gt ', ' pretime ' = Time (), ' preip ' = ' 127.0.0.1 ',]; User::create ($data); Insert a new record and return the saved model instance return redirect ('/');}

Register.blade

<form class= "Login-form" action= "" method= "POST" > {!! Csrf_field ()!} 

5. Middleware – Users must be logged in

Now that the registration has been completed, we will be poor user's judgment. The requirement registration account must only be an account with Super Administrator privileges to register.

In this case, according to our general step is to detect the user's information directly in the Postregister method, and then check whether the user satisfies this permission, and then jumps to the other page without satisfying the situation.

This method is possible, however, since we have a super Admin and administrator these permissions are differentiated, certainly more than one place to use, other places will be used.

Then someone will want to model write a method in the future can be called directly.

This method is also possible, however, we recommend using the middleware provided by Laravel, which is very powerful and very useful. Now we're going to use middleware as a function.

Because we are the back-end content management system, we first create a middleware, the function is, all pages before entering, must be logged in, otherwise skip to the login page.

View manual discovery You can use the php artisan make:middleware CheckLoginMiddleware command to create a middleware, of course, copy a similar file, change is the same.

Then app/Http/Middleware/ we create a middleware file in the directory CheckLoginMiddleware , there is only one handle() method, we add our function directly inside

<?phpnamespace app\http\middleware;use closure;use auth;class checkloginmiddleware{Public function handle ($ Request, Closure $next) {  //using Auth method, need to introduce use Auth; method  //$request->is (' login ') indicates whether the requested URL is a login page  // Because we are going to use the global, so we need to exclude the login page, otherwise infinite redirect  //If your login page is not/login, but/auth/login, write $request->is (' auth/login ')  // And we want to perform its task after the request processing, because we need to obtain the user's login information  $response = $next ($request);  if (! Auth::check () && $request->is (' login ') {   return redirect ('/login ');  }  return $response; }}

The function of this middleware is, if there is a route generated, first use Auth::check() to determine whether the user is logged in, if there is no login jump to the login page.

method is written well, but can not be used, we need to register this middleware, tell the framework of our middleware is written, can be used, the scope of use.

app/Http/there is a file in the directory to Kernel.php register the middleware, that is, to tell the framework, we have written this middleware.

Kernel.phpin the file, there are two array properties, one $middleware for global use, and one for the $routeMiddleware choice to use.

Global use means that the middleware will be executed first, regardless of which page you request.

Select the usage representation, which HTTP request is required, where the middleware is executed, and where it executes.

Each page here requires a login, it is necessary to register a global, in the $middleware array attributes to add a

\app\http\middleware\checkloginmiddleware::class

Under registration, you can use the

> Note: Remember, if you want to be extra careful when defining the global, such as above we want to exclude the login page, or because the user is not logged in, so on which page will be redirected to the login page, of course, including the landing page

6. Middleware – Special pages need to validate user groups

Now is the limit of the user Rights page, and we also need to re-create a middleware

Use php artisan make:middleware CheckGroupMiddleware to create a new middleware to determine whether the user satisfies this permission

<?phpnamespace 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); }}

Here we still through Auth::user() to obtain the user's information, and then judge the user's group, does not belong to the Super administrator to jump to the homepage.

Then we app/Http/ have a file in the directory to Kernel.php register the middleware, this time we are registered as a choice of middleware.

This middleware is optional, so we also need to give it an individual name, in addition to the array attributes such as a $routeMiddleware bar

' User.group ' = \app\http\middleware\checkgroupmiddleware::class

Create a middleware that can be used with usergroup this name.

Once created, we can choose where to use, one to add in router.php the routing file, and one to use in controller the

Used in router.php files

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

Used within the controller

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

Here we choose to add middleware in the route. Make the registration page only a Super administrator to register

Route::get (' register ', ' Usercontroller@getregister ')->middleware (' User.group '); Route::p ost (' register ', ' Usercontroller@postregister ')->middleware (' User.group ');

We currently only have two routes to judge the permissions, so the use of the chain style, of course, you can also follow the manual in the way the group, the way more elegant groups.

Of course, if the method in your entire controller requires middleware for validation filtering, you can also create a group form, or you can use the method directly within the controller, __construct so that each time the controller is requested, the middleware is executed first

Class Mycontroller extends controller{public function __construct () {  $this->middleware (' User.group '); function index () {  return view (' My.index ');}}

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

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.