问题
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:
run command php artisan make:middleware Middlewarename
and you'll find your middleware insideapp/Http/Middleware/yourcustomemiddleware.php
- Register your middleware in
app/Http/kernel.php
file which you just created - 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');
}
- 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