Laravel Episode 9: Middleware Roles

episode 9

Episode 9: Middleware Roles
  • Create a migration file for staff role and default staff account.
php artisan make:migration create_staff_role_and_default_new_user
  • Code the new migration file.
public function up()
{
    // create new staff role
    DB::table('roles')->insert(
        [
            'id'                 => 2,
            'role_name'          => 'staff'
        ]
    );

    // create default user for staff
    DB::table('users')->insert(
        [
            'username'      => 'staff',
            'email'         => 'staff@test.com',
            'password'      => Hash::make('password'),
            'role_id'       => 2,
            'created_at'    => CarbonCarbon::now()->toDateTimeString(),
            'updated_at'    => CarbonCarbon::now()->toDateTimeString()
        ]
    );
}

public function down()
{
    // delete staff user account
    DB::table('users')->where('username', 'staff')->delete();

    // delete staff role
    DB::table('roles')->where('id', '2')->delete();
}
  • Create new middleware for roles
php artisan make:middleware RoleMiddleware
  • Edit Role.php model.
use User;
use Auth;
use Redirect;

public static function userHasRole($role_name)
{
    if (Auth::check())
    {
        $check_role = User::select('roles.role_name')
            ->join('roles', 'roles.id', '=', 'users.role_id')
            ->where('users.id', Auth::User()->id)
            ->where('roles.role_name', $role_name)
            ->first();
        if ($check_role)
        {
            return true;
        }else{
            return false;
        }
    }

    return false;
}
  • Edit the middleware file /app/Http/Middleware/RoleMiddleware.php.
use AppModelsRole;
use Redirect;

public function handle($request, Closure $next, $role)
{
    // check if user has role being checked
    if (! Role::userHasRole($role))
    {
        // redirect to access denied page
        return back()->with('error', 'Access Denied');
    }

    return $next($request);
}
  • Add the new middleware to the /app/Http/Kernel.php.
'role' => AppHttpMiddlewareRoleMiddleware::class,
  • Apply it in a controller.
public function __construct()
{
    $this->middleware('role:admin');
}
  • You can redirect to a custom view if you wish.
  • You can have specific methods apply middleware.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.