Skip to content
Advertisement

Can U use the middleware the same way in the controller or route?

I’m trying to make sure that you can’t just type /admin into the top bar. I made an extra column in the user table called admin and it’s either 0 (normal user) or 1 (admin).

In the blade page, I’m checking:

@if (Auth::check())
  @if (Auth::user()->admin == 1)
   <p>Hello Admin</p>
  @else
   <p>Hello standard user</p>
  @endif
@endif

I was asking if it’s possible to either check in the route (something like this)

Route::get('/home', 'HomeController@index')->name('home')->middleware('auth')-where('admin' 1); 

or in the controller (something like this)

public function __construct()
{
   $this->middleware('auth')->where('admin' 1);
}

Advertisement

Answer

You can achieve this using a new middleware.

First create a new middleware by typing in your console:

php artisan make:middleware isAdmin

Name your middleware whatever you like, isAdmin is common here.

Next you must add the middleware to your Kernel.php located at app/Http/Kernel.php, edit the array named $routeMiddleware and add the following:

'isAdmin' => AppHttpMiddlewareIsAdmin::class,

Open your IsAdmin.php located in your middleware folder and modify the handle method like so:

{
     if (Auth::user() &&  Auth::user()->admin == 1) {
            return $next($request);
     }

    return redirect('/');
}

Note: the middleware will also check if a user is authenticated so could be used in place of auth for admin routes, remember to modify the return to suit your needs

Lastly, add the middleware to your route, there are a number of ways to do this.

  • if you are planning to use it instead of auth middleware, simple change auth to isAdmin in your routes file ->middleware('isAdmin')
  • Another option is to modify your routes file like so
Route::group(['middleware => 'auth'], function () {
    Route::get('/home', 'HomeController@index')->name('home')->middleware('isAdmin');
}

So you don’t need to apply the middlewares to each route, there are a bunch of possibilities for this here https://laravel.com/docs/7.x/middleware#assigning-middleware-to-routes

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement