Laravel give user access to specific route when conditions are met

风格不统一 提交于 2019-12-11 15:58:41

问题


Laravel 5

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

For example let user access

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

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


回答1:


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

The following steps are required to do this:

  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:

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. Attach middleware to your route:

routes/web.php:

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

All done now your route is secured.

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.



来源:https://stackoverflow.com/questions/52901316/laravel-give-user-access-to-specific-route-when-conditions-are-met

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!