Setting up different User and Admin logins in Laravel

This is the first thing that you need to do immediately after setting up laravel. Almost every application needs a User and a Admin front-end. The real question is where to put the admin data. Technically there are two ways by which you can do it. The first one is having the User/Admin data in one table only ( which is already provided by Laravel). Its easy to manage. The 2nd method is to do separate login tables, i.e. users and admin tables.

I’m a bit reluctant to take the 2nd route. First, you need to have two sets of models, irrespective of the framework you are using. Secondly, its not much of an advantage since you are going to have only 10-20 admins or staff members at most. However, in architectures where there is Admin->User->Client, one must opt for different login tables for clients.

Ok coming to the point now. I assume that Laravel is installed and set-up. If not, please follow this earlier tutorial: http://kgfog.com/2016/06/17/laravel-installation-on-linux-mint/

The first thing you’d like to do is edit the .env file. That’s where your database details will go. Edit these lines to provide your DB and User/Pass details

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=monger
DB_USERNAME=monger
DB_PASSWORD=p@ssw0rd

After that you need to run the migrate command so that all the migrations can be applied successfully. Simply run:

php artisan migrate

Now you should see 3 tables in the MySQL database, migrations, users and password_resets

Before doing anything, lets make use of a wonderful laravel command which makes a basic auth scaffold for us. With this we can register a user and use it as a base for checking our admin vs user auth.

$ php artisan make:auth
Created View: /home/imnica/Personal/Projects/monger/resources/views/auth/login.blade.php
Created View: /home/imnica/Personal/Projects/monger/resources/views/auth/register.blade.php
Created View: /home/imnica/Personal/Projects/monger/resources/views/auth/passwords/email.blade.php
Created View: /home/imnica/Personal/Projects/monger/resources/views/auth/passwords/reset.blade.php
Created View: /home/imnica/Personal/Projects/monger/resources/views/auth/emails/password.blade.php
Created View: /home/imnica/Personal/Projects/monger/resources/views/layouts/app.blade.php
Created View: /home/imnica/Personal/Projects/monger/resources/views/home.blade.php
Created View: /home/imnica/Personal/Projects/monger/resources/views/welcome.blade.php
Installed HomeController.
Updated Routes File.
Authentication scaffolding generated successfully!

We’ll have to edit the existing migration to create a column which will identify the admin. My frog chose “superuser” a boolean type.

We’ll create a new migration here. Note that this is necessary to roll back the changes, so make it a habit to create a migration out of every change 😉

php artisan make:migration add_admin_to_users_table --table=users

Edit the migrations file in database/migrations/ It should look like this:

<?php

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

class AddAdminToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->boolean('superuser');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('superuser');
        });
    }
}

Do a artisan migrate and you’re good to go to the next step.

Lets make a middleware now. Your middleware will be saved in app/Http/Middleware/ directory.

php artisan make:middleware Admin

Edit the middleware and match the code to this:

<?php

namespace App\Http\Middleware;

use Closure;

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

        return redirect('home');
    }
}

Done!!! Now lets add this middleware to Kernel.php file found in app/Http folder

protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'admin'=>\App\Http\Middleware\Admin::class
    ];

Last thing, make changes to your app/User.php to accomodate isAdmin function

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function isAdmin()
    {
        return $this->superuser;
    }
}

That’s it. Now you can add admin auth to any page and it will ask for Authentication before access. For example, lets go to the scaffold that Laravel created for us. Register 2 users there, and make 1 user superuser using mysql (only this time, since we haven’t added any User management features YET!)

To test, open up the app/Http/route.php file and add this line:

Route::get('/admin', ['as' =>'admin.page', 'uses' => 'HomeController@adminonly', 'middleware' => ['auth', 'admin']]);

And put a simple function in the HomeController.php created by scaffold ( in app/Http/Controllers/HomeController.php


public function adminonly()
    {
        echo "Protected Page";
    }


Now if you try to login with a user with superuser = 0, it will redirect you to home page. A admin can see the message Protected Page.

Ofcourse you can make your own changes, redirect them to “Access Denied” or something. Up to you 🙂

Let me know if there are any questions in the comments section. Peace!!

Thanks
Mohit