0

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!");
    }
user10145145
  • 33
  • 1
  • 7
  • In the middleware, you should redirect user if his role is not admin what is the meaning of checking `auth()->user()->role == 0` this condition in the middleware. middleware logic should be proper, if user's role is admin then go to next otherwise redirect to home with error – Shailendra Apr 07 '21 at 06:12

1 Answers1

0

// Like above

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

// OR you can do individually

`Route::group(['middleware' => ['role:admin']], function () {
    Route::get('/products',[ProductController::class,'index'])->middleware('role:cashier');
    Route::post('/products',[ProductController::class,'index'])->middleware('role:manager');
});`
Hoang Le
  • 78
  • 3