中间件的应用
控制器
<?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');
}
}
}
原文地址:https://blog.csdn.net/2301_80189168/article/details/143427633
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!