Laravel 5 Basics (12)-certification-php Tutorial

Source: Internet
Author: User
Laravel5 Basics (12)-authentication Laravel factory already has a user authentication system. let's take a look at routes. php. if it is deleted, add: Route: controllers ([& #39; auth & #39; & gt; & #39; AuthAuthController & #39 ;, & #39; password & #39; & gt; & #39 Laravel 5 Basics (12)-authentication

Laravel already has a user authentication system. let's take a look.routes.phpIf yes, add:

Route::controllers([    'auth' => 'Auth\AuthController',    'password' => 'Auth\PasswordController']);

Availablephp artisan route:listCheck it out. Access in the browser/auth/login, You can see the login interface, it is best to set the default systemapp.blade.phpOr else you will go crazy.

You can use register, login, or even forget password.

Actually registering a user fails after submission, but it does not actually fail, but larave automatically jumps/home, We have deleted this controller. You can usetinkerCheck that the user has already created an ECS instance.

InAuth\AuthControllerActually usedtraitWhat is triat? Well, php only supports single inheritance. with trait added in php5.4, a trait is actually a group of methods, and you can include it in another class. Such as an abstract class. you cannot instantiate it directly.

InAuth\AuthControllerReferences to trait:

use AuthenticatesAndRegistersUsers;

Let's find him and see how he jumps after registration. He hides deeply invendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesAndregistersUsers.php, Wow.

Public function redirectPath () {if (property_exists ($ this, 'redirectpath') {return $ this-> redirectPath;} // if the user sets the redirectTo attribute, jump to the property set by the user. Otherwise, go to homereturn property_exists ($ this, 'redirectto ')? $ This-> redirectTo: '/home ';}

OK. Now we know, just setredirectToThis property can be customized after registration. InAuth\AuthContotrollerModify:

 protected $redirectTo = 'articles';

Use/auth/logoutMake sure that we exit. if something goes wrong, do not be afraid. we don't have the default homepage. visit again:auth/registerCreate a new user. this time it should be OK.

Logout again, and then use login to log on.

Now we can deleteform_partialAnd then modify the controller:

Public function store (Requests \ ArticleRequest $ request) {// you can do this // $ request = $ request-> all (); // $ request ['User _ id'] = Auth: id (); // simpler method $ article = Article :: create ($ request-> all (); // laravel automatically completes the external key association Auth: user ()-> articles ()-> save ($ article ); return redirect ('articles ');}

Add an article and then usetinkerCheck it out.

Middleware

Of course, we do not want anyone to post articles, at least for login. We add protection in the controller:

    public function create() {        if (Auth::guest()) {            return redirect('articles');        }        return view('articles.create');    }

The above code can work. there is a problem. we need to handle it in every method that requires protection. this is too silly. Fortunately, we have middleware.

The middleware can be understood as a processing pipeline. the middleware can process at a certain time point in the pipeline, which can be a request or a response. Requests may be redirected or passed based on the processing rules of the middleware.

Inapp/http/middlewareContains three middleware, so you can see what you are doing by name. take a good look. note,Closure $nextRepresents the next middleware.

Inapp/http/kernel.phpRegister the middleware.$middlewareSection declares the middleware that processes all http requests,$routeMiddlewareOnly process the route, and you must display the declaration to use one or more of the middleware.

Suppose we wantArticlesControllerFor protection, we directly add middleware in the constructor:

    public function __construct() {        $this->middleware('auth');    }

Now, all methods are protected.

But we may not want the entire controller to be protected. what if it is only one or two of them? We can handle it like this:

Public function _ construct () {$ this-> middleware ('auth', ['only' => 'create']); // of course, this can be reversed. // $ this-> middleware ('auth', ['couldn't '=> 'index']);}

We do not necessarily introduce middleware in the controller constructor. we can directly declare in the routing:

Route::get('about', ['middleware' => 'auth', 'uses' => '[email protected]']);

Inkernel.phpSystem middleware provided in, such'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode'Yes, we can enter the maintenance mode. for example, the system is online, but now we need to temporarily close it for a while. we can process it in the command line and take a look at the work of this Middleware:

php artisan down

Visit the website and you can see that any url request is immediately back. Website Launch:

php artisan up

Let's make our own middleware:

 php artisan make:middleware Demo

Then add the code:

Public function handle ($ request, Closure $ next) {// if the request contains foo, we will return to the controller homepage if ($ request-> has ('Foo ')) {return redirect ('Articles ');} return $ next ($ request );}

If you want to use middleware for all requests, you mustkernel.phpIn$middlewareMedium registration:

protected $middleware = [...'App\Http\Middleware\Demo',];

Now let's test it. suppose we access/articles/create?foo=bar, We are redirected to the home page.

Let's remove this display middleware and create a truly useful middleware. Suppose we want to protect a page, which must be accessible by managers.

php artisan make:middleware RedirectIfNotAManager

Let's add the processing code:

public function handle($request, Closure $next){        if (!$request->user() || !$request->user()->isATeamManager()) {            return redirect('articles');        }return $next($request);}

Modify our model as follows:

    public function isATeamManager() {        return false;    }

For simplicity, false is returned directly. This time we place the middleware inkernel.phpIn$routeMiddleware.

protected $routeMiddleware = [...'manager' => 'App\Http\Middleware\RedirectIfNotAManager',];

Let's test the route:

Route::get('foo', ['middleware' => 'manager', function() {    return 'This page may only be viewed by manager';}]);

The home page is returned when you access the guest or logon identity.isATeamManager()Returntrue, You can see the returned information when you access the logon identity.

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.