Skip to main content

Laravel 5.4 (and 5.5) native User Authentication + Role Authorization

A very brief step-by-step of how to implement a native Laravel 5.4 user authentication + role authorization.
Starting from a fresh Laravel 5.4/5.5 installation,
run the php artisan to create the Auth resource:
  1. $ php artisan make:auth
Create the Role model and respective migration (-m parameter):
  1. $ php artisan make:model Role -m
Edit CreateRolesTable class in the migrations folder:
  1. public function up()
  2. {
  3. Schema::create(‘roles’, function (Blueprint $table) {
  4. $table->increments(‘id’);
  5. $table->string(‘name’);
  6. $table->string(‘description’);
  7. $table->timestamps();
  8. });
  9. }
  10. public function down()
  11. {
  12. Schema::dropIfExists(‘roles’);
  13. }
Create a new migration for the role_user pivot table :
  1. $ php artisan make:migration create_role_user_table
Edit CreateRoleUserTable class in the migrations folder:
  1. public function up()
  2. {
  3. Schema::create(‘role_user’, function (Blueprint $table) {
  4. $table->increments(‘id’);
  5. $table->integer(‘role_id’)->unsigned();
  6. $table->integer(‘user_id’)->unsigned();
  7. });
  8. }
  9. public function down()
  10. {
  11. Schema::dropIfExists(‘role_user’);
  12. }
Now let’s provide a many-to-many relationship between User and Role
Open User model and add the following method:
  1. public function roles()
  2. {
  3. return $this->belongsToMany(Role::class);
  4. }
Do the same with Role model:
  1. public function users()
  2. {
  3. return $this->belongsToMany(User::class);
  4. }
It’s time to create some seeders to add roles and users in the database:
  1. $ php artisan make:seeder RoleTableSeeder
  2. $ php artisan make:seeder UserTableSeeder
Edit RoleTableSeeder class (database/seeds/ folder) adding the following code in
run() method:
  1. use Illuminate\Database\Seeder;
  2. use App\Role;
  3. class RoleTableSeeder extends Seeder
  4. {
  5. public function run()
  6. {
  7. $role_employee = new Role();
  8. $role_employee->name = employee’;
  9. $role_employee->description = A Employee User’;
  10. $role_employee->save();
  11. $role_manager = new Role();
  12. $role_manager->name = manager’;
  13. $role_manager->description = A Manager User’;
  14. $role_manager->save();
  15. }
  16. }
Do the same with UserTableSeeder class:
  1. use Illuminate\Database\Seeder;
  2. use App\User;
  3. use App\Role;
  4. class UserTableSeeder extends Seeder
  5. {
  6. public function run()
  7. {
  8. $role_employee = Role::where(‘name’, employee’)->first();
  9. $role_manager = Role::where(‘name’, manager’)->first();
  10. $employee = new User();
  11. $employee->name = Employee Name’;
  12. $employee->email = employee@example.com’;
  13. $employee->password = bcrypt(‘secret’);
  14. $employee->save();
  15. $employee->roles()->attach($role_employee);
  16. $manager = new User();
  17. $manager->name = Manager Name’;
  18. $manager->email = manager@example.com’;
  19. $manager->password = bcrypt(‘secret’);
  20. $manager->save();
  21. $manager->roles()->attach($role_manager);
  22. }
  23. }
Edit DatabaseSeeder class (database/seeds/ folder) adding the following code in
run() method:
  1. public function run()
  2. {
  3. // Role comes before User seeder here.
  4. $this->call(RoleTableSeeder::class);
  5. // User seeder will use the roles above created.
  6. $this->call(UserTableSeeder::class);
  7. }
Almost done! Don’t give up! ^^
Open User model and add these three tiny methods:
  1. /**
  2. * @param string|array $roles
  3. */
  4. public function authorizeRoles($roles)
  5. {
  6. if (is_array($roles)) {
  7. return $this->hasAnyRole($roles) ||
  8. abort(401, 'This action is unauthorized.');
  9. }
  10. return $this->hasRole($roles) ||
  11. abort(401, 'This action is unauthorized.');
  12. }
  13. /**
  14. * Check multiple roles
  15. * @param array $roles
  16. */
  17. public function hasAnyRole($roles)
  18. {
  19. return null !== $this->roles()->whereIn(‘name’, $roles)->first();
  20. }
  21. /**
  22. * Check one role
  23. * @param string $role
  24. */
  25. public function hasRole($role)
  26. {
  27. return null !== $this->roles()->where(‘name’, $role)->first();
  28. }
Open app/Http/Controllers/Auth/RegisterController.php and change the create() method to set a default Role for new Users:
  1. use App\Role;
  2. class RegisterController ...
  3. protected function create(array $data)
  4. {
  5. $user = User::create([
  6. 'name' => $data['name'],
  7. 'email' => $data['email'],
  8. 'password' => bcrypt($data['password']),
  9. ]);
  10. $user
  11. ->roles()
  12. ->attach(Role::where('name', 'employee')->first());
  13. return $user;
  14. }

Run the migrate command with seed parameter. Next time you login, each user should have a role.
  1. $ php artisan migrate:fresh --seed
Finally the final step!
Now, all you need to do is call the User authorizeRoles() method inside your Controller Actions or Middlewares and pass an array with the user roles you want to grant access.
  1. class HomeController extends Controller
  2. {
  3. public function __construct()
  4. {
  5. $this->middleware('auth');
  6. }
  7. public function index(Request $request)
  8. {
  9. $request->user()->authorizeRoles(['employee', 'manager']);
  10. return view(‘home’);
  11. }
  12. /*
  13. public function someAdminStuff(Request $request)
  14. {
  15. $request->user()->authorizeRoles('manager');
  16. return view(‘some.view’);
  17. }
  18. */
  19. }
After this point, just proceed with the normal development flow. Build a interface CRUD to manage roles and assign them to the users.
Source: Medium

Comments

Popular posts from this blog

15 Movies That Made Audiences Leave The Theater

15 Movies That Made Audiences Leave The Theater : Source:  Screenrant Forking over an hour or two of pay makes going to see a film a burden on the wallet, even if theater chains maintain that it's cheaper than ever to go to the movies. Most moviegoers want to see a film they know they will enjoy to avoid throwing away their hard-earned cash, so when movies sometimes leave audiences feeling disgruntled, disgusted or even ill enough to walk out, it's a big deal. Even some of the staunchest movie-goers who refuse to leave the theater for any reason sometimes find themselves walking out of a production for the strangest excuses. Whether or not the theater will refund tickets paid for movies that upset or sicken audiences, hundreds of people have walked out of startling films for plenty of reasons. Sometimes it's mind-boggling. For those who wanted a scary movie, why bail when it gets too scary? Whatever happened to turning your head? Then there are the people who never re...

Tallulah Movie Review & Film Summary (2016)

Tallulah | Source:  Rogerebert When writer/director Sian Heder introduced “Tallulah” at this year’s past Sundance Film Festival, it was revealed that she was around six months pregnant during production. She also shared that when she received the call about the festival accepting her film, her sentiment was more or less “Cool … I have a baby on my boob.” Heder’s movie, playing in select theaters and available on Netflix, is unabashedly about this very physical and emotional commitment to the life-changing event of motherhood, conveyed with an albeit drawn-out story. In its greatest achievement, Heder's writing and directing of “Tallulah” articulates—or feels like it does, to my humbled, male eyes—the intangible sacrifice and stresses of motherhood. Heder’s script is narratively ambitious with this mission, centered on a stolen baby and three moms who are bad in ways different to this week’s mainstream comedy release “Bad Moms.” Ellen Page plays Tallulah (shortened to “Lu”), a...

What is the advantage of DIV over P?

There are different kinds of elements (block, inline, table...). Example for block elements are: h1, p, div, ... Examples for inline elements are: em, block, span, ... An block element can contain inline elements and text. Some block elements can contain also other block elements (like div) while others cannot (like p). Block elements start a new line in the text flow. Inline elements can contain other inline elements and text but not block elements. Inline elements do not start a new line in the text flow. Since <p> is an block element which should not contain other block elements you shouldn't use a <div> inside. Use the <span> here. You can't use the div there legally. It's a block element. Span is inline. Source:  Stackoverflow