laravel内置了一个中间件来验证用户是否通过认证,若是用户没有通过认证,中间件会将用户重定向到登陆页面,不然若是用户通过认证,中间件就会容许请求继续往前进入下一步操做。php
固然,除了认证以外,中间件还能够被用来处理更多其它任务。好比:CORS 中间件能够用于为离开站点的响应添加合适的头(跨域);日志中间件能够记录全部进入站点的请求。html
Laravel框架自带了一些中间件,包括认证、CSRF 保护中间件等等。全部的中间件都位于 app/Http/Middleware
目录。laravel
中间是请求前仍是请求后执行取决于中间件自己,如下中间件会在请求处理前执行一些任务跨域
<?php namespace App\Http\Middleware; use Closure; class TestMiddle { public function handle($request, Closure $next) { // 执行动做 if(!$request->session()->has('huser')){ return redirect("login/index"); } return $next($request); } }
而下面这个中间件则会在请求处理后执行其任务:session
<?php namespace App\Http\Middleware; use Closure; class TestMiddle { public function handle($request, Closure $next) { $response = $next($request); // 执行动做 if(!$request->session()->has('huser')){ return redirect("login/index"); } return $response; } }
中间件能够本身在编辑器里面新建对应类生成,也可用命令生成app
php artisan make:middleware TestMiddle
此时,laravel的app\Http\Middleware\目录就会多一个TestMiddle.php的中间件文件框架
此时中间件还不能直接使用,必须把它注册到咱们的laravel中,以下编辑器
只需在 app/Http/Kernel.php
类(3个属性,对应里面加入,我有时用路由的)spa
'TestMiddle' => \App\Http\Middleware\TestMiddle::class,
Route::get('/',function(){ return redirect('home/index'); })->middleware('TestMiddle');
Route::group(['middleware' => ['TestMiddle']], function() { Route::controller("db","DataBaseController"); });
Route::controller("home","HomeController",['middleware'=>'TestMiddle']);
http://www.cnblogs.com/fwqblogs/p/6641569.html日志