Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ifimhereibrokeit's avatar

My first middleware - roles in Laravel 5.3

Hello there. I'm painfully new to Laravel. My only experience thus far has been following along with the DevMarketer Blog tutorial and Mindspace's ACL tutorial.

I'm attempting to implement my first middleware in accordance with what's in the docs rather than what I've seen done in videos to no avail.

Here's my check roles middleware.

<?php

namespace App\Http\Middleware;
use App\Role;
use App\User;
use Closure;

class CheckRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->user() === null) {
            return response("Whoops, doesn't look like you have permissions. Log back in and then try again.", 401);
        }
        $actions = $request->route()->getAction();
        $roles = isset($actions['roles']) ? $actions['roles'] : null;

        if ($request->user()hasAnyRole($roles) || !$roles) {
            return $next($request);
        }
        
        return response("Whoops, doesn't look like you have permissions to be here. Log back in and then try again.", 401);
    }
}

The route I'm testing with within web.php looks like so

Route::get('/contact', 'PagesController@getContact')->middleware('roles');

And finally, here's my PagesController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

class PagesController extends Controller
{
 public function getContact() {
        return view('pages.contact');
    }
}

I'm attempting to use these Blade statements:

{{ $user->hasRole('User') ? 'You are a user' : '' }}
                    { $user->hasRole('Moderator') ? 'You are a mod' : '' }}
                    { $user->hasRole('Operator') ? 'You are a operator' : '' }}

Does anyone see why this is throwing a 500 error? If I had more to go off of, I might be able to troubleshoot this alone.

0 likes
0 replies

Please or to participate in this conversation.