Simplifying Admin Panel Creation in Laravel 10 Using Middleware

Spread the love

Laravel 10: We frequently need to create an admin panel to restrict access to specific application operations to administrators alone. This post will show us how to leverage middleware to speed up the process.

Follow the steps to create admin Panel in Laravel 10

Step 1: Update the existing users migration to include a column ‘is_admin’

To create an admin panel in Laravel, we must first add a new column called "is_admin" to the existing users migration file. This column will be utilized to assess whether or not a user has administrative access. To do so, navigate to 'database/migrations/create_users_table.php' and add the following line inside the 'up' method:

$table->boolean('is_admin')->default(false);

As a result, a new boolean column with the default value of false, 'is_admin' will be added to the users database. To apply this change to your database, remember to run the migration with the the following command:

php artisan migrate

Step 2: Create a seeder to seed an Admin User

The following step is to write a seeder that will insert an admin user into our users table. Laravel provides a practical way to generate seeders by using the 'make:seeder' Artisan command. After you’ve opened your terminal or command prompt, type the following command:

php artisan make:seeder AdminSeeder

The 'database/seeders' directory will now contain a brand-new seeder file with the name 'AdminSeeder.php'. Open this file, then add the following code to its contents:

use Illuminate\Database\Seeder;
use App\Models\User;

class AdminSeeder extends Seeder
{
    public function run()
    {
        User::create([
            'name' => 'Admin',
            'email' => 'admin@example.com',
            'password' => bcrypt('password'),
            'is_admin' => true,
        ]);
    }
}

In this example, we’ll create an admin user named "Admin" with the email address "admin@example.com" the password "password" and the "is_admin" column set to true. You are free to change these settings to suit your requirements.

Use the following command to run this seeder and add the admin user to your database:

php artisan db:seed --class=AdminSeeder

This will execute the run method defined in your seeder class and insert the admin user into your users table.

Step 3: Create a Route Users which will list all the users

Now that we’ve created our admin account, let’s make a route that lists all of the users in our application. Add the following line to your ‘routes/web.php’ file:

Route::get('/admin/users', UserController::class)->name('admin.users');

A 'GET' request to '/admin/users' will be sent to the 'UserController' class via this route. If your controller class name is different, replace 'UserController' with it.

Step 4: Create a Controller ‘Admin/UserController’

We need create a new controller called 'UserController' to handle this route. In your terminal or command prompt, type the following command:

php artisan make:controller Admin/UserController

This will create a new controller file called 'UserController.php' in the directory 'app/Http/Controllers/Admin'. Replace the contents of this file with the following code:

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;

class UserController extends Controller
{
    public function __invoke()
    {
        $users = User::paginate(10);

        return view('admin.users', compact('users'));
    }
}

In this example, we utilize the User model to retrieve all users from the database and paginate them with 10 people per page. We then give these users to the 'admin.users' view. Check that the matching blade view file is located at 'resources/views/admin/users.blade.php'.

Step 5: Create a middleware ‘IsAdmin’

We need to construct a custom middleware name'IsAdmin' to restrict access to our admin routes to just authenticated admin users. In your terminal or command prompt, type the following command:

php artisan make:middleware IsAdmin

This will create a new middleware file called 'IsAdmin.php' in the directory 'app/Http/Middleware'. Replace the contents of this file with the following code:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->user() && $request->user()->is_admin) {
            return $next($request);
        }

        abort(404);
    }
}

In this example, we’ll write a middleware called 'IsAdmin' to determine whether the authenticated user has admin access. The middleware will enable the request to proceed if the user is an administrator. Otherwise, a 404 error will be returned.

Step 6: Register this Middleware

Open your 'app/Http/Kernel.php' file and add the following line to the '$routeMiddleware' array to register our new middleware:

'admin' => \App\Http\Middleware\IsAdmin::class,

This will assign the alias 'admin' to our 'IsAdmin' middleware.

Step 7: Add the middleware in the Route

Now that our middleware has been registered, we can use it to secure our administrative routes. Add the following line to your 'routes/web.php' file:

Route::get('/admin/users', UserController::class)->name('admin.users')->middleware('admin');

Our 'IsAdmin' middleware will now secure this route. Non-admin users will be sent to a 404 error page if they attempt to access this route.

Step 8: Access Route after log in using normal user

To put our new middleware to the test, navigate to the '/admin/users' route using a regular user account. Because normal users do not have admin rights, you should receive a 404 error page.

Step 9: Access Route after log in using Admin User

Next, utilize your admin account to navigate to the '/admin/users' route. You should now see a list of all the users in your application.

Conclusion

In this tutorial, we learned how to use middleware to create an admin panel in Laravel 10. We updated our users migration file to include a 'is_admin' column, built a seeder to populate our database with an admin user, built a route and controller to list all users in our application, built a custom middleware to limit access to our admin routes to only authenticated admin users, and tested our new middleware by logging in as both a normal user and an admin user.

You can quickly construct an admin panel for your Laravel 10 application and restrict access to important features to just authorized users by following these instructions.

Many times we need to upload files in out app and store them in storage along with the path in database. I’ve created a article Mastering File Uploads in Laravel Validation and Database Storage where I discussed about uploading files in in details and simple way.