Creating Admin Middleware in Laravel 5.3

Creating Admin Middleware in Laravel 5.3

Here is a basic guide to creating a Middleware in Laravel 5.3 that will protect your routes to only Admin Access. Using Laravel Artisan Command create a Middleware called isAdmin
php artisan make:middleware isAdmin
In App/Http/Middleware directory open the file isAdmin.php
namespace App\Http\Middleware;
use Closure;
class isAdmin {
    public function handle($request, Closure $next)
    {
        if ( Auth::check() && Auth::user()->isAdmin() )  {
            return $next($request);
        }
        return redirect('home');
    }
}
Now go to your Kernel.php in App/Http.
protected $routeMiddleware = [
    'auth' => 'App\Http\Middleware\Authenticate',
    'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
    'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
    'isAdmin' => 'App\Http\Middleware\isAdmin',
];
In routes/web.php you can now add your admin route check. Anything inside this will need Admin credentials. Here is an example below.
//Is Admin Check
Route::group(['middleware' => ['auth', 'isAdmin']], function(){

  Route::get('/admin', [
    'uses' => 'AdminController@index',
    'as' =>'admin'
  ])
});;
Next step is to create a migration so.
php artisan make:migration add_is_admin_to_user
Add this to your newly created migration in database/migrations.
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddIsAdminToUser extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function($table) {
            $table->integer('is_admin')->after('name')->default(0);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function($table) {
            $table->dropColumn('is_admin');
        });
    }
}
In your App/User.php add a check for isAdmin.
public function isAdmin()
{
    return $this->is_admin; // return the is_admin column using 1 for true 0 for false
}
Then amend the is_admin for the user you want to give the privileges to in the database or add a function to your CMS.

Categories: Posts