laravel中间件使用总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40018938/article/details/80922404

laravel中间件的使用:

创建中间件命令
php artisan make:middleware CheckLogin
执行完以上命令会在app/Http/Middleware目录下创建一个新的中间件类CheckLogin.php。
创建完以后还需要注册中间件在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,
        //这就是新注册的中间件
        'checklogin' => \App\Http\Middleware\CheckLogin::class,

    ];
可以在刚创建的中间件里写验证如下:
<?php

namespace 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);
    }
}
接着就是怎么使用中间件功能了
Route::group(['namespace'=>'Admin','middleware'=>'checklogin'],function (){
    Route::get('admins','IndexController@index');
    Route::get('logout','IndexController@logout');
});

这里直接使用的是路由群组,只要把路由放在群组之中都会经过这个验证,[‘namespace’=>’Admin’]是命名空间,[‘middleware’=>’checklogin’]这就是中间件验证,之前注册时注册名为checklogin,所以middleware后直接写checklogin就可以了。

feedLoading.gif

没有更多推荐了,返回首页

原创
25
粉丝
2
喜欢
1
评论
0
等级:
访问:
1万+
积分:
343
排名:
27万+
勋章:

持之以恒

授予每个自然月内发布4篇或4篇以上原创或翻译IT博文的用户。不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累!
'); (window.slotbydup = window.slotbydup || []).push({ id: "u3032528", container: s }); })();

博客年龄

'); (window.slotbydup = window.slotbydup || []).push({ id: "u3163270", container: s }); })();

此为网页(blog.csdn.net)快照,查看来源