Laravel Episode 10: More Middleware and Routes

episode 10

Episode 10: More Middleware and Routes


  • Laravel Debugbar by barryvdh
    • Works with Laravel 4 and 5.
    • Great tool for sql profiler among other things.
  • Review the previous episode regarding multiple roles middleware.
    • Middleware implementation is not the same as how I implemented filters from previous version of Laravel.
    • Use Debugbar how the SQL looks with current implementation of RoleMiddleware().
  • Possibly rewrite Role::userHasRole() to User::hasRoles() like the example from Laravel’s website.
  • Explain how to apply multiple middlewares for each route but for my example, it isn’t working as expected.
  • Restful routing may not be used with implementation that is chosen.
    • Possibly have to recode forms from CRUD to match new routes.
  • Show Route Groups

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
            'id'                 => 2,
            'role_name'          => 'staff'

    // create default user for staff
            'username'      => 'staff',
            'email'         => '',
            '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', '', '=', 'users.role_id')
            ->where('', Auth::User()->id)
            ->where('roles.role_name', $role_name)
        if ($check_role)
            return true;
            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()
  • You can redirect to a custom view if you wish.
  • You can have specific methods apply middleware.