This article mainly introduces the use of Laravel middleware, has a certain reference value, and now share to everyone, the need for friends can refer to
Use of Laravel middleware:
Create middleware commands
PHP Artisan Make:middleware Checklogin
Executing the above command will create a new middleware class checklogin.php under the App/http/middleware directory.
After creation, you also need to register the middleware in app/http/kernel.php:
protected $routeMiddleware = [ ' auth ' = = \illuminate\auth\middleware\authenticate::class, ' auth.basic ' = > \illuminate\auth\middleware\authenticatewithbasicauth::class, ' bindings ' = \illuminate\routing\ Middleware\substitutebindings::class, ' can ' = = \illuminate\auth\middleware\authorize::class, ' guest ' = > \app\http\middleware\redirectifauthenticated::class, ' throttle ' = \illuminate\routing\middleware\ Throttlerequests::class, //This is the newly registered middleware ' checklogin ' and \app\http\middleware\checklogin::class, ];
You can write validation in the middleware you just created as follows:
<?phpnamespace app\http\middleware;use closure;use illuminate\support\facades\session;class CheckLogin{ /** * Handle an incoming request. * * @param \illuminate\http\request $request * @param \closure $next * @return Mixed * /Public Function handle ($request, Closure $next) { $userid = session::get (' _userid '); $login _sts = session::get (' _login_sts '); if (Empty ($userid) | | empty ($login _sts)) { return response ()->view (' Admin/login '); } Return $next ($request);} }
And then how to use the middleware function
Route::group ([' namespace ' = ' Admin ', ' middleware ' = ' checklogin '],function () { route::get (' admins ', ' Indexcontroller@index '); Route::get (' logout ', ' indexcontroller@logout ');});
The direct use of the routing group here, as long as the route is placed in the group will pass this verification, [' namespace ' + ' Admin '] is a namespace, [' middleware ' = ' checklogin '] This is the middleware validation, Before registering the registered name is Checklogin, so middleware directly after the Checklogin can be written.
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!