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.
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 inside app/Http/Middleware/yourcustomemiddleware.php
app/Http/kernel.php
file which you just createdYourMiddlewareClassCode:
/**
* 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');
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With