Hi, i am new to Laravel and as of my knowledge i have tried to Create a basic laravel application with default Laravel’s Registration, Login/Logout. But interms of Roles i have created three roles like:-
Where all these roles will work with authentication + authorization, Like say suppose you have logged in as a Student and when you try to access teacher’s functionality or URL. It will restrict So, I have done this using Middleware, Routes in Laravel Below i am giving a brief Explanation.
- Install Laravel more info(https://laravel.com/docs/5.8/installation).
- Next open command prompt where you have installed your Laravel Project and type Composer Update. So that if any of your package was not installed during laravel installation, it will get installed.
- Now copy .env.example to .env and generate key for Laravel (php artisan key:generate). So it would have generated key. Also update your Database Name, Username, Password. And check whether your app is working. Assuming you have created Database.
- Now add a column in user’s migration table (Located in database/migrations/2014_10_12_000000_create_users_table.php) like user_role with enum datatype with values like admin,student,teacher and migrate.
- Now create 3 middlewares and 3 controllers like AdminMiddleware, StudentMiddleware, TeacherMiddleware, Controllers like AdminController, StudentController, TeacherController.
6. Next in your Routes create route by middleware grouping and write the route inside each grouped route say for example:-
Route::group([‘middleware’ => ‘App\Http\Middleware\AdminMiddleware’], function()
Route::group([‘middleware’ => ‘App\Http\Middleware\TeacherMiddleware’], function()
Route::group([‘middleware’ => ‘App\Http\Middleware\StudentMiddleware’], function()
7. I hope you are able to understand the above routing.
8. Next create the functions in respective controller. And also some modification is needed in Middleware say for example ill show the AdminMiddleware code below.
9. Create respective view files too.
10. Finally run the application, Login as student and try to access teachers url or admin url surely you will be able to see a page where it will tell that its restricted.
For the existing application find the github link below
A simple application all about managing multiple roles in laravel by using multiple middleware for multiple roles …
Thanks, And sorry for my grammatical mistake and if the above tutorial is not good or not a good practice please correct me.
Thanks once again