1. 如何定义中间件?
? ? ? ? 1> 在app\Http\Middleware文件夹下创建中间件php
<?php
namespace App\Http\Middleware;
use App\Http\Controllers\Controller;
use Closure;
use Illuminate\Http\Request;
class Activity{
public function handle(Request $request, Closure $next){
if(time() < strtotime('2022-04-10')){
return redirect('activity0');
}
return $next($request);
}
}
? ? ? ? 2> 将新创建的中间件名字添加到kernel.php 中2.
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
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,
'activity'=> \App\Http\Middleware\Activity::class, // 添加的中间件
];
2. 如何使用中间件
? ? ? ? 1> 在路由中可以这样定义
/*
* 中间件,如果当前时间没有到达某一天,则活动不开始
* **/
Route::get('activity0', 'StudentController@activity0');
Route::group(['middleware'=>['activity']], function(){
Route::get('activity1', 'StudentController@activity1');
Route::get('activity2', 'StudentController@activity2');
});
? ? ? ? ?2> 定义对应的controller
public function activity0(){
echo '活动即将开始,敬请期待';
}
public function activity1(){
echo '活动进行中,我是活动1';
}
public function activity2(){
echo '活动进行中,我是活动2';
}