Sam Comber
Sam Comber

Reputation: 1293

Enable only admin to view page in Laravel

I'm trying to enable only admin users to be able to view certain contents of a navbar in my laravel project. I have a users table with a role column consisting of 'admin' and 'user' values which I use in my middleware to allow admin users to access an admin panel for CRUD operations.

I've tried:

@if(auth()->check())
 @if(Auth::user()->get(array('users.role')) == 'admin')

  'THIS IS WHAT I WANT ONLY ADMIN USERS TO SEE!'

 @endif
@endif

Yet, when logged into an 'admin' user, I still can't see admin-only content. I'm fairly new to the framework, but if anyone has any advice I would highly appreciate it!

Thanks,

Sam

Upvotes: 4

Views: 6918

Answers (2)

Sanzeeb Aryal
Sanzeeb Aryal

Reputation: 3266

You can create a separate admin middleware group:

 public function handle($request, Closure $next, $guard = null)
    {
        if(Auth::check())
        {
            if($request->user()->role=='admin')
            {
               return $next($request);
            }
             return redirect('/');    
        }

        return redirect('/login');
    }

so that you can protect the routes which only admins are allowed:

Route::group(['middleware' => ['App\Http\Middleware\Adminmiddleware']], function () {
             //admin routes

    });

for your code, you can check with:

if(Auth::user()->role == 'admin')

Upvotes: 7

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Try this:

@if (Auth::user() && Auth::user()->role == 'admin')
    'THIS IS WHAT I WANT ONLY ADMIN USERS TO SEE!'
@endif

Auth::user() is the same as Auth::check() and it will check if user is authenticated. Only if user is authenticated, Laravel will run Auth::user()->role == 'admin' which will check if user is an admin.

Upvotes: 7

Related Questions