Laravel 控制器的middleware中间件

场景:活动开始前只能访问宣传页面,开始后才可以访问其他页面:

步骤:

新建中间件,

注册中间件,

使用中间件,

中间件的前置和后置操作。

 

控制器:

public function activity0(){
return '活动快要开始啦,敬请期待';
}
public function activity1(){
return '活动页面1';
}
public function activity2(){
return '活动页面2';
}

路由:
Route::any('activity0',['uses'=>'StudentController@activity0']);
Route::any('activity1',['uses'=>'StudentController@activity1']);
Route::any('activity2',['uses'=>'StudentController@activity2']);

在App\Http\Middleware下创建中间件Activity.php:
namespace App\Http\Middleware;
use Closure;

class Activity{
public function handle($request,Closure $next){
if(time() < strtotime('2018-01-01')){
return redirect('activity0');
}
return $next($request);
}
}

//注册中间件,在Kernel.php中的$routeMiddleware数组中增加
protected $routeMiddleware = [
'activity' => \App\Http\Middleware\Activity::class,
];


使用中间件,路由中的设置
//宣传页面不需要中间件验证,不能放里边
Route::any('activity0',['uses'=>'StudentController@activity0']);

Route::group(['middleware'=>['activity']],function(){
Route::any('activity1',['uses'=>'StudentController@activity1']);
Route::any('activity2',['uses'=>'StudentController@activity2']);
});



//后置中间件
public function handle($request,Closure $next){
$response = $next($request);
echo $response;
echo '我是后置操作';
}

 

posted @ 2018-05-15 16:00  学知无涯  阅读(2697)  评论(1编辑  收藏  举报