mardi 6 avril 2021

Role Based access to routes in laravel

In the below I want to access the route get product only if the user role is admin. How can I do that?

User Model in database

 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('role');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

Product Model

public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->string('description')->nullable();
            $table->decimal('price',5,2);
            $table->timestamps();
        });
    }

Api.php

Route::group(['middleware' => ['authentic']], function () {
    Route::get('/products',[ProductController::class,'index']);
});

AdminMiddleware

public function handle($request, Closure $next)
    {
        if(auth()->user()->role == 'admin'){
            return $next($request);
        } else if(auth()->user()->role == 0){
            return $next($request);
        }
        return redirect('home')->with('error', "You have no proper authentication to access the area!");
    }


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire