'Laravel same route for different middlewares
I have problem with routes and middlewares. I have 5 middleware roles. Administravimas, birstonas_biblioteka, druskininkai_biblioteka, birstonas_registratura,druskininkai_registratura.
The problem is that some same routes can access several roles. But when i declare same route to different middlewares only one of them can access and when i use or in routes with multiple middlewares then every roles can access route.
Middlewares code Administravimas:
class Administravimas
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$userRoles = Auth::user()->roles()->pluck('pavadinimas');
//$collection = DB::table('roles_users')->select('*')->get
//dd($userRoles);
if(!$userRoles->contains('Administravimas'))
{
return redirect('/prieiga-nesuteikta');
}
return $next($request);
}
}
Middlewares code birstonas_registratura
public function handle($request, Closure $next)
{
$userRoles = Auth::user()->roles()->pluck('pavadinimas');
//$collection = DB::table('roles_users')->select('*')->get
//dd($userRoles);
if(!$userRoles->contains('Birštonas registratūra'))
{
return redirect('/prieiga-nesuteikta');
}
return $next($request);
}
Web routes :
Route::group(['middleware' => 'Administravimas' OR 'birstonas_registratura'], function () {
Route::get('books', 'BookController@index')->name('books');
Route::post('books', 'BookController@add')->name('book.add');
});
Kernel:
'Administravimas' => \App\Http\Middleware\Administravimas::class,
'birstonas_biblioteka' => \App\Http\Middleware\BirstonasBiblioteka::class,
'druskininkai_biblioteka' => \App\Http\Middleware\DruskininkaiBiblioteka::class,
'birstonas_registratura' => \App\Http\Middleware\BirstonasRegistratura::class,
So how i declarate same route only for some groups not for all.
Solution 1:[1]
You can pass parameters to middleware, so you can make a middleware that you can pass the name of all the roles you want to allow:
public function handle($request, $next, ...$roles)
{
$userRoles = Auth::user()->roles()->pluck('pavadinimas');
foreach ($roles as $role) {
if ($userRoles->contains($role)) {
// they have the current iterated role
// let them pass through
return $next($request);
}
}
// they don't have any of these roles
// redirect away
}
Then assigning your middleware:
`rolescheck:Admin,student`
Using what you currently have as a base example.
Solution 2:[2]
$userRoles = Auth::user()->roles()->pluck('pavadinimas')
Above why using pluck & pavadinimas is field name? why we are using this
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | lagbox |
Solution 2 | pooja |