控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AgeController extends Controller
{
//
public function index(){
return "年龄测试";
}
}
路由
// 年龄控制器路由
Route::get("d2/{age}",[AgeController::class,"index"])->middleware(CheckAge::class);
// Route::get("d2/{age}",[AgeController::class,"index"])->middleware(被使用的中间件的名字);
// 中间件重定向的路由
Route::get('d3',function(){
return "你输入的年龄 <= 18";
});
创建中间件
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckAge
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if($request->route('age') > 18){
return $next($request);
/** return $next($request); 下一步, 继续向后走,继续
* 向后访问控制器、视图、匿名函数等各种资源*/
}else{
return redirect('d3');
}
}
}