Jimmyjbk
Jimmyjbk

Reputation: 411

How do I restrict routes to a certain user on laravel

I have added a role column to my auth user which extended the role table

Role migration

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('roles');
    }
}

user migration

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->unsignedInteger('role_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

In my roles I have Admin, and three other different users. I would like to restrict some routes to only the admin.

routes

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::resource('/admin', 'AdminController');

Route::resource('/farm', 'FarmController');

Route::resource('/clinic', 'ClinicController');

Route::resource('/slaughter', 'SlaughterController');

Route::get('/home', 'HomeController@index')->name('home');

How can I deal with that, restrict the route using admin controller to only the admin

Upvotes: 4

Views: 2997

Answers (1)

Tharaka Dilshan
Tharaka Dilshan

Reputation: 4499

One of the good approach is create a Middleware to restrict routes.

  1. Create Middleware
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class AuthorizedAdmin
{
    public function handle($request, Closure $next)
    {
        if (!$this->isAdmin($request)) {
            abort(Response::HTTP_UNAUTHORIZED);
        }

        return $next($request);
    }

    protected function isAdmin($request)
    {
        // Write your logic to check if the user us admin.

        // something like
        return $request->user()->role->description == 'Admin';
    }
}
  1. Register Middleware

Add this middleware class to $routeMiddleware array in the App\Http\Kernel

Kernel

protected $routeMiddleware = [
    ... // other middlewares
    'admin' => \App\Http\Middleware\AuthorizedAdmin::class,
];
  1. Wrap routes with this middleware.

routes.php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::middleware('admin')->group(function () {

   // All your admin routes go here.

   Route::resource('/admin', 'AdminController'); 
});

Route::resource('/farm', 'FarmController');

Route::resource('/clinic', 'ClinicController');

Route::resource('/slaughter', 'SlaughterController');

Route::get('/home', 'HomeController@index')->name('home');

Upvotes: 5

Related Questions