How To Create A Super Admin And Admin In Laravel?

In order to start a Laravel website we need to have admin roles first –a super admin and an admin. Then the users can register and login on their own but the very first 2 users must be an admin and the super admin. Here is how we can implement that.

1. Updating CreateUserTable migration

We need to add is_permission column in our users table. Here is the full code.

<?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->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
	        $table->tinyInteger('is_permission')->default(3);
	        $table->timestamps();
        });
    }

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

Then run migration

php run migration

This will create users table with permissions. You should check in database before moving on to the next step.

2. Updating DatabaseSeeder and running it

Then you need to place this code in DatabaseSeeder.php and it must create 2 users. Emily as Super admin and Ryan as admin. You can change accordingly and also email and password.

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
	    App\User::create([
		    'name' => 'Emily',
		    'email' => '[email protected]',
		    'password' => \Illuminate\Support\Facades\Hash::make('[email protected]'),
		    'is_permission' => 1
	    ]);

	    App\User::create([
		    'name' => 'Ryan',
		    'email' => '[email protected]',
		    'password' => \Illuminate\Support\Facades\Hash::make('[email protected]'),
		    'is_permission' => 2
	    ]);
    }
}

Then run seeder to create super admin and admin in users table.

php artisan db:seed

Now you may try to login. If you will register any other user he will be logged in as user with is_permission value 3. And that is all which we need to do.  If you face any problem, please leave a comment.