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就可以了。

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