Support the ongoing development of Laravel.io →
Authentication Security Validation

I'm an absolute beginner in Laravel 5.

I've created a middleware class called BeforeMiddleware the blueprint of that class is below.

class BeforeMiddleware { public function handle($request, Closure $next, $role) { if($request->user()->hasRole($role)){ return redirect('/pensions'); } return $next($request); } } registered in kernel.php as

protected $routeMiddleware = [ 'auth' => 'App\Http\Middleware\Authenticate', 'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth', 'guest' => 'App\Http\Middleware\RedirectIfAuthenticated', 'role' => 'App\Http\Middleware\BeforeMiddleware', ]; User model is below

class User extends Model { public function hasRole($name) { return ($this->role->name == $name) ? true : false; }

public function role()
{
    return $this->belongsTo('App\Models\Role');
}

} and usage in routes.php is below.

Route:get('/reporting', [ 'middleware' => 'role:Owner', 'uses' => function(){ return 'secret data only be viewable by the owners'; }]); If I open that in the browser /reporting I get the following error.

ReflectionException in Container.php line 776: Class role:Owner does not exist HOWEVER if I hard code 'Owner' in middleware and remove the $role parameter and also removed it from routes which now looks like this.

BeforeMiddleware.php

class BeforeMiddleware { public function handle($request, Closure $next, $role) { if($request->user()->hasRole($role)){ return redirect('/pensions'); } return $next($request); } } routes.php

Route:get('/reporting', [ 'middleware' => 'role', 'uses' => function(){ return 'secret data only be viewable by the owners'; }]); it works as desired...

therefore my question is how to pass that parameter when using middleware to control routes

Any Idea?

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

sh4rif sh4rif Joined 13 Jun 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.