Adding a super admin/super user to an application is extremely helpful. It can allow you to build features such as controlling options in the app that only a few trusted users should be allowed to update, block access to a particular user, and much more.
Adding logic to allow you to start protecting routes or functionality in your app is super easy and can be broken into 3 steps.
## 1. Attach a role to a user
This can be achieved in more than one way; creating a “**_role_**” model and then a “**_role_user_**” pivot table to create a relationship between a user and a role, or using a package such as [Spatie’s Laravel Permissions package](<[https://spatie.be/docs/laravel-permission/v5/introduction](https://spatie.be/docs/laravel-permission/v5/introduction)>). We’ll keep it simple by adding a new “**_is_admin_**” column to the users table.
```bash
php artisan make:migration add_is_admin_column_to_users_table
```
```php
// database/migrations/2022_03_31_204217_add_is_admin_column_to_users_table.php
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->boolean('is_admin')->default(false);
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('is_admin');
});
}
```
Remember to run the migration after:
```bash
php artisan migrate
```
Let’s quickly make sure we add our new column to the “**_fillable_**” property on our model and also make sure we are casting this attribute as a boolean:
```php
// app/Models/User.php
protected $fillable = [
'name',
'email',
'password',
'is_admin'
];
protected $casts = [
'is_admin' => 'boolean',
];
```
## 2. Create a middleware
Next, we can create a middleware that will handle the check on each request by a user to see if they are an admin. We can then use this middleware on any routes in our application that we want to protect.
```bash
php artisan make:middleware CheckIsAdmin
```
You can send the user wherever you like in your application if they aren’t an admin, I’ll send them to the dashboard route for now:
```php
// app/Http/Middleware/CheckIsAdmin.php
public function handle(Request $request, Closure $next)
{
if (!auth()->user()->is_admin) {
return redirect(route('dashboard'));
}
return $next($request);
}
```
Next, let’s register our new middleware in the kernel:
```php
// app/Http/Kernel.php
protected $routeMiddleware = [
...,
'is_admin' => \App\Http\Middleware\CheckIsAdmin::class,
];
```
## 3. Protect a route
No we can use this to protect any route we like in our app! For example:
```php
// routes/web.php
Route::middleware(['is_admin'])->group(function () {
// my protected routes
Route::get('users', [UserController::class, 'index'])->name('users.index');
});
```
Easy as that!