Laravel在条件满足时为用户提供访问特定路线的权限 [英] Laravel give user access to specific route when conditions are met

查看:58
本文介绍了Laravel在条件满足时为用户提供访问特定路线的权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Laravel 5

Laravel 5

在满足某些条件时如何授予用户访问特定路由的权限?

How to give user access to specific route when certain conditions are met?

例如,让用户访问

Route::get(view('posts/{id}'),'PostsController@show');

当用户的用户"->积分"列中的积分超过100时.

when user has over 100 points in his user->points column.

推荐答案

您可以使用中间件为此,在Laravel中,通过创建自己的中间件来保护您的路由非常容易.

You can use Middleware for this,In Laravel it is very easy to secure your routes by creating your own middlewares.

需要执行以下步骤:

  1. run command php artisan make:middleware Middlewarename,您将在app/Http/Middleware/yourcustomemiddleware.php
  2. 中找到中间件
  3. 在您刚刚创建的app/Http/kernel.php文件中注册您的中间件
  4. 现在在刚创建的中间件中实现逻辑:
  1. run command php artisan make:middleware Middlewarename and you'll find your middleware inside app/Http/Middleware/yourcustomemiddleware.php
  2. Register your middleware in app/Http/kernel.php file which you just created
  3. Now implement logic in middleware you just created:

您的MiddlewareClassCode:

YourMiddlewareClassCode:

/**
 * 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');
}

  1. 将中间件附加到您的路由:

routes/web.php:

routes/web.php:

Route::get(view('posts/{id}'),'PostsController@show')->middleware('yourcustommiddleware');

现在所有操作都已完成.

All done now your route is secured.

摘要::中间件中的此语句return $next($request);将在条件匹配时返回该路由,否则它将重定向到先前的路由.

Summary: this statement return $next($request); in middleware will return the route when condition is matched else it will redirect to the previous route.

注意::我不知道您的数据库结构,这只是一个示例,向您展示什么是中间件,中间件如何工作以及如何使用它.

Note: I don't know your db structure and also this is just an example to show you that what is middleware and how it works and how you can use it.

这篇关于Laravel在条件满足时为用户提供访问特定路线的权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆