jeudi 6 juin 2019

Checking the user's role in Laravel

I am beginner in Laravel. I have project in Laravel 5.8.

I have this code:

Middleweare:

class CheckRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $role)
    {
        if (! $request->user()->hasRole([$role])) {
            if( $role == 'admin' || $role== 'receptionist' || $role == 'adminCompany' || $role == 'telemarketer')
            {
                return redirect('/cms');
            }
            else
            {
                return redirect()->route('index');
            }

        }

        return $next($request);
    }
}

Seeder:

public function run()
    {
        DB::table('roles')->insert([
            'name' => 'admin'
        ]);
        DB::table('roles')->insert([
            'name' => 'adminCompany'
        ]);

        DB::table('roles')->insert([
            'name' => 'telemarketer'
        ]);

        DB::table('roles')->insert([
            'name' => 'receptionist'
        ]);

        DB::table('roles')->insert([
            'name' => 'user'
        ]);

        DB::table('roles')->insert([
            'name' => 'userPremium'
        ]);

        DB::table('roles')->insert([
            'name' => 'userCompany'
        ]);

        DB::table('roles')->insert([
            'name' => 'userSponsor'
        ]);

        DB::table('roles')->insert([
            'name' => 'userGuest'
        ]);

    }

Schema:

Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });

and my web.php:

Route::group(['prefix' => 'admin'], function () {
    Route::get('/', 'BackendController@index')->name('adminHome')->middleware('CheckRole:user,CheckRole:userPremium,CheckRole:userCompany,CheckRole:userSponsor,CheckRole:userGuest');
});

I would like the CheckRole middleware to check if the user has the following roles: user, userPremium, userCompany, userSponsor, userGuest for route adminHome. At the moment, Laravel only checks 1 role - not all.

How repair it?



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2WPXnWX
via IFTTT

Aucun commentaire:

Enregistrer un commentaire