C
C
ChertyakaNUB2020-10-18 17:44:01
Laravel
ChertyakaNUB, 2020-10-18 17:44:01

How to use two roles in middleware?

Hello!

Laravel 8.

There are roles in the project and the roles have middleware:

...
 public function handle($request, Closure $next, ... $roles)
    {
dd($roles);
...

Applying different roles in the route in the middleware itself:
Route::get('/page', [PageController::class, 'index'])->name('page')->middleware('role:admin,manager');

I get on the landing page with the help of check(dd($roles);), only one role in the array, the last one: manager.
5f8c551704ea6353683051.png
Where does admin disappear to, who can tell what is wrong with the code?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
ChertyakaNUB, 2020-10-18
@ChertyakaNUB

I realized that there are no simple solutions, there are only crutches:
1 Method, use several parameters:
in the route:

Route::get('/page', [PageController::class, 'index'])->name('page')->middleware('role:admin,manager');

in middleware:
...
public function handle($request, Closure $next, $role1, $role2)
    {
//Используем уже здесь $role1, $role2
...

2 Method, use one parameter with delimiter:
in route:
Route::get('/page', [PageController::class, 'index'])->name('page')->middleware('role:admin|manager');

in middleware:
...
public function handle($request, Closure $next, $role)
    {
if (!is_array($role)) {
      $roles = explode('|', $role);
    }
...

Crutches, not crutches, but the solution works.
If suddenly geeks find a more elegant / correct solution, write!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question