• notice
  • Congratulations on the launch of the Sought Tech site

About the use of Middleware in laravel

    laravel5 started to have middleware, middleware is not a complicated thing, but Once packaged in laravel, it becomes a tall thing.For example, do all user center pages require users to log in before they can see it, then here is a middleware that can be extracted to determine whether it is a logged-in user.It is actually that simple.

Suppose we have such a route in routes.php:

Route::get('/', ' homeController@index ');
Route::group( ['prefix' =>'usercenter','namespace' =>'UserCenter' ,'middleware' =>'usercheck'], function()
{
    Route::get ('/user', ' userController@index');
});
To enter the URL prefixed with usercenter page (actually call the namespace< span>UserCenter under the controller) must go through the middleware: middleware filtering, then we need to configure middleware in Kernel.php, that is, what is middleware:usercheck in routes.php.As follows:

protected $routeMiddleware = [
        //Enter the user center to verify middleware
    ;    'usercheck' => \App\Http\Middleware\UserCheck::class,
    ];
Actually here is to tell laravel, usercheck this middleware is to call App\Http\Middleware\UserCheck class only.Then enter the class: App\Http\Middleware\UserCheck< /span>

namespace App\Http\Middleware;
use Closure;
class UserCheck
{< br>     public function handle($request, Closure $next, $guard = null)
    {
        
        if (whether the user is logged in)
        {
            return redirect('/login');//Jump Go to the login page
        }
   
//Here you can add some numbers to $request such as
        $request ->userid = user ID.Then bring this variable to the user center controller
 
        return $next($request);
    }
}


This class is to judge whether the user is logged in, if not logged in, all jump to the login interface, if the login is successful, go to the next step (this next step is the page that the user really wants to visit, here it is easy to understand this usercheck is It plays such a role in the middle, so it is named middleware).Just a reminder.When you jump to the next step, you usually have to pass some data in the past.You can write the data in the request, or you can define static variables in this class to take it to the next step.

Tags

Technical otaku

Sought technology together

Related Topic

1 Comments

author

brand atorvastatin 20mg & lt;a href="https://lipiws.top/"& gt;order generic atorvastatin 80mg& lt;/a& gt; atorvastatin 10mg pills

Wvyzve

2024-03-07

Leave a Reply

+