cie*_*u97 4 routes conditional-statements laravel
拉拉维尔 5
当满足某些条件时如何让用户访问特定路线?
例如让用户访问
Route::get(view('posts/{id}'),'PostsController@show');
Run Code Online (Sandbox Code Playgroud)
当用户在其用户->积分栏中拥有超过 100 分时。
您可以为此使用中间件,在 Laravel 中,通过创建自己的中间件可以很容易地保护您的路由。
为此,需要执行以下步骤:
run command php artisan make:middleware Middlewarename你会在里面找到你的中间件 app/Http/Middleware/yourcustomemiddleware.phpapp/Http/kernel.php在您刚刚创建的文件中注册您的中间件您的中间件类代码:
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->points >= 100)
{
return $next($request);
}
return redirect()->back()->with('flash_message','you are not allowed to access this');
}
Run Code Online (Sandbox Code Playgroud)
路线/web.php:
Route::get(view('posts/{id}'),'PostsController@show')->middleware('yourcustommiddleware');
Run Code Online (Sandbox Code Playgroud)
现在一切都已完成,您的路线已安全。
摘要:中间件中的这条语句return $next($request);将在条件匹配时返回路由,否则将重定向到上一个路由。
注意:我不知道您的数据库结构,这只是一个示例,向您展示什么是中间件、它如何工作以及如何使用它。
| 归档时间: |
|
| 查看次数: |
2562 次 |
| 最近记录: |