Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel give user access to specific route when conditions are met

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.

like image 995
cieniu97 Avatar asked Oct 15 '25 15:10

cieniu97


1 Answers

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.

like image 184
Salman Zafar Avatar answered Oct 18 '25 07:10

Salman Zafar