Example detailed Laravel registration refactoring _php Skills

Source: Internet
Author: User

1. First determine the user registered route

When we install the Laravel, the default generated registration is registered with the mailbox, and some options are not required, some also need to add some form options

We are not registered, can not be casually registered, only some super administrator to register

First we use the last created UserController configuration, and if not, you can use the 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 to display a registered page get request, followed by the registration account post request.

2. Show registered Account page

This is the getRegister method that only needs to display a view so there is no particular logic

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

3. Request Registration Account

This is the way it is used. postRegister

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

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

$dataIs the array that holds the key and value of each field.

Public Function Postregister (Request $request) {$rules = [' username ' => ' required|unique:finance_enewsuser ', ' pas
 Sword ' => ' required|between:6,20|confirmed '];  $messages = [' Required ' => ': attribute cannot be empty ', ' unique ' => ' username has been registered ', ' between ' => ' password must be between 6~20 bits ', ' confirmed '
 => ' New password and Confirm password does 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, ' Password ' => bcrypt ($password), ' GroupID ' => $group, ' checked ' =&G T 0, ' Styleid ' => 1, ' Filelevel ' => 0, ' Loginnum ' => 0, ' Lasttime ' => time (), ' Lastip ' => ' the 127.0.0.
 1 ', ' truename ' => ', ' email ' => ', ' Pretime ' => time (), ' Preip ' => ' 127.0.0.1 ',]; User::create ($data); Inserts a new record and returnsThe saved model instance//If you want to log in immediately after registering, you can use $user = User::create ($data); Auth::login ($user);
For authentication return redirect ('/'); }

4. After completion of the example

Usercontroller

Public Function Getregister () {return view (' Auth.register ');} Public Function Postregister (Request $request) {$rules = [' username ' => ' required|unique:finance_enewsuser ', '
 Word ' => ' required|between:6,20|confirmed '];  $messages = [' Required ' => ': attribute cannot be empty ', ' unique ' => ' username has been registered ', ' between ' => ' password must be between 6~20 bits ', ' confirmed '
 => ' New password and Confirm password does 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, ' Password ' => bcrypt ($password), ' GroupID ' => $group, ' Chec Ked ' => 0, ' Styleid ' => 1, ' Filelevel ' => 0, ' Loginnum ' => 0, ' Lasttime ' => time (), ' LA Stip ' => ' 127.0.0.1 ', ' truename ' => ', ' email ' => ', ' pRetime ' => time (), ' Preip ' => ' 127.0.0.1 ',]; User::create ($data);
Inserts a new record and returns the saved model instance return redirect ('/'); }

Register.blade

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

5. Middleware – Users must log in

Now that the registration is complete, we are on the wrong user's judgment. The requirement registration account must only have Super Administrator rights account to be able to register.

In this case, according to our general step is in the Postregister method directly identify the user's information, and then see if the user satisfies this permission, not satisfied with the case to jump to other pages.

This can be, but we have a super admin and admin to distinguish between these rights, certainly more than one place to use, other places will be used.

Then someone will think model of a way to write a method that can be invoked directly in the future if necessary.

This method is also possible, however, we recommend the use of the middleware provided by Laravel This feature is very powerful and very useful. Now we're going to use the middleware feature.

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

View the manual found that 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 a app/Http/Middleware/ middleware file is created in the directory, and there CheckLoginMiddleware 's only one handle() way in which we can add our functionality directly inside.

<?php

namespace App\http\middleware;

Use Closure;
Use Auth;

Class Checkloginmiddleware
{public
 function handle ($request, Closure $next)
 {
  //using the Auth method, you need to introduce use Auth method
  //$request->is (' login ') indicates whether the requested URL is a login page
  //Because we intend to use the global, so we need to exclude the login page, otherwise it will be infinite redirect
  ///If your login page is not/ Login, but/auth/login words, write $request->is (' auth/login ')
  //And we will perform its task after the request is processed 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 that if there are routes generated, first use to Auth::check() determine whether the user is logged in, if there is no login to jump to the login page.

Method is written, but not yet available, we need to register this middleware, tell the framework of the middleware we have written, can be used, the scope of use.

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

And Kernel.php there are two array properties in the file, one $middleware for global use and one for the $routeMiddleware option to use.

Global use means that no matter which page you request, you will implement this middleware first.

Select Use to indicate which HTTP request is required to execute the middleware and where to execute it.

Here each page requires that you must log in, you can register a global, in the $middleware array attribute to add a

\app\http\middleware\checkloginmiddleware::class

Registered, you can use the

> Note: keep in mind that if you define the global, be careful, such as the above we want to exclude the login page, or because the user is not logged in, so the page will be redirected to the login page, of course, including landing page

6. Middleware – Special pages need to validate user groups

Now is the limit of the user Rights page, we also have to recreate a middleware

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

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

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

Then we app/Http/ have a file in the directory that Kernel.php registers this middleware, and this time we register as a middleware to choose from.

This middleware because it is optional, so we also need to give it an individual name, in the $routeMiddleware array attribute Riga as a

' 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 join in router.php the routing file, one to use in the controller

Use in router.php files

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

Use within the Controller

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

Here we choose to add middleware to the route. Make the registration page can only be a super administrator to register

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

We currently have only two routes to determine permissions, so we use a chained style, of course, you can also follow the manual in the way the group, the way the group is more elegant.

Of course, if your entire controller method requires the middleware to verify the filter, you can also create the form of the group, you can also directly in the controller to use the __construct method, so that each request this controller, the first implementation of middleware

Class Mycontroller extends Controller
{public
 function __construct ()
 {
  $this->middleware (' User.group ');
 }

 Public Function Index ()
 {return
  view (' My.index ');
 }

Summarize

The above is laravel registration of all the content, I hope the content of this article for everyone to use laravel can help, if there is a question welcome to the message discussion, small series will give you a reply as soon as possible.

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.