Any application needs a login system if it has user specific resources, here we will see how you can add a login system in laravel application. There are two ways you can implement a login system in laravel.
- Using Laravel Inbuilt Auth System
- Manually Writing Auth System
While using an inbuilt auth system is fast and easy to implement, manually writing your own logic for authentication gives you more flexibility. We will see both ways of implementation and then you can decide which way is best for your use case.
Implementing Authentication Using Laravel Built In Auth System
Since laravel 6.0, All UI portion has been moved to laravel/ui package, So first we need to install it in our project
composer require laravel/ui
Once installed you can run following command to generate auth scaffolding
php artisan ui bootstrap --auth
We are using a simple bootstrap template here, But there are also options to generate scaffoldings for the vue & react framework directly.
If you are working with laravel version lower than 6.0 then you have to use following
php artisan make:auth
But in older versions only a simple layout is available, but you can modify it to make it work with other frameworks like vue or react.
Now that we have generated basic auth scaffolding, we can navigate to http://localhost:8000/login to check our newly generated login page, But wait, why is there no style? It’s because all views generated by command usage app.css & app.js files but these files will not be available by default. You can change it to your custom style file if you want or we can generate this file using Laravel Mix, Laravel Mix is an assets compiler, basically it compiles SASS & LASS style to Css, mergies/compile JS files in a single browser ready file.
You might have noticed that we have not added any route but url still works! It’s because of Auth::routes(); thas is added in your web.php
This register following routes for you :
// Authentication routes $this->get('login', 'Auth\LoginController@showLoginForm')->name('login'); $this->post('login', 'Auth\LoginController@login'); $this->post('logout', 'Auth\LoginController@logout')->name('logout'); // Registration routes $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register'); $this->post('register', 'Auth\RegisterController@register'); // Password reset routes $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request'); $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email'); $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset'); $this->post('password/reset', 'Auth\ResetPasswordController@reset')->name('password.update'); // Password confirmation routes $this->get('password/confirm', 'Auth\ConfirmPasswordController@showConfirmForm')->name('password.confirm'); $this->post('password/confirm', 'Auth\ConfirmPasswordController@confirm'); // Email verify routes $this->get('email/verify', 'Auth\VerificationController@show')->name('verification.notice'); $this->get('email/verify/{id}/{hash}', 'Auth\VerificationController@verify')->name('verification.verify'); $this->post('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');
You can also configure which route you would like to add, for ex, if you want to disable registration then use following
Auth::routes(['register' => false]);
It takes following options : register, reset, confirm, verify
You can find its implementation at vendor\laravel\ui\src\AuthRouteMethods.php
Using Laravel Mix to generate app.css & app.js files
First install all dependency using
npm install
And then run
npm run dev
This command will compile your assets and app.css and app.js will be available, now if you refresh your login page you will be able to see a nice looking login page
In development you will be using npm run watch instead of npm run dev, npm run watch will continue to watch for any changes you make in your style and js files and will recompile automatically if any changes detected, It is very helpful while designing and writing js logic or working any frontend framework like vue or react.
With this our working authentication system is ready, But before we can use this, we need to make some basic configuration.
Configure your database
You will need to set credentials for your database server in .env file
DB_CONNECTION=mysql DB_HOST=your_db_server_address DB_PORT=3306 DB_DATABASE=your_db_name DB_USERNAME=your_db_username DB_PASSWORD=your_db_password
Now that your database is configured, We need to configure the auth.php file.
First thing you will notice in auth.php is this
'defaults' => [ 'guard' => 'web', 'passwords' => 'users', ]
This specifies that by default we will use ‘web’ guard, configuration of this guard is provided below in ‘guards’ property, which has by default web & api, we will only see web for now as in laravel you mostly will use web unless you are implementing API endpoints as well.
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', 'hash' => false, ], ]
For web guard, driver is session, means authentication state will be maintained in sessions and provider is ‘users’, This provider is also has separate property below
'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\User::class, ], // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ],
Provider has one provider by details and it’s ‘users’, we are currently using this and generally you don’t need another provider but you can add another provider as well if needed.
In provider, We have driver which can have two values “database” & “eloquent”, For now we are going to use eloquent as driver but you can use database as well, and based on your configured driver you have to set model Or table name as shown above, In case of eloquent we have to set our modal class with namespace, This modal will be used for login, registration and password reset. If you are using a database as driver then you have to add table property and set it to your specific table name, This table will be used for login, registration and password reset.
Now, There is ‘passwords’ as well, This property is used for configuring your password reset location.
'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_resets', 'expire' => 60, // This link will expire in 60 minutes 'throttle' => 60, // User can request for password reset one time only in 60 seconds ], ],
We have ‘users’ in passwords which specify the provider that is ‘users’ and table which is the name of the table that will be used for storing reset password information. It also has other useful configurations like expire and throttle. Expire specifies how long your password reset link is valid and throttle specifies how much delay should be there before requesting another reset link.
By default laravel auth system will use following table structure
User table
id | name | email_verified_at | password | remember_token | created_at | updated_at | |
Password reset table
token | created_at | |
You can change this table structure but for that modification will be required in controllers, you can check our other post for customizing laravel’s default authentication.
That’s it, Now you can register one user and try login in it with your newly generated login details.
Protecting your routes
Now that our login system is working, we have to protect our routs/view that should be accessed only if a user is logged in. We can implement this by using auth middleware.
Now that our login system is working, we have to protect our routs/view that should be accessed only if a user is logged in. We can implement this by using auth middleware.
We can directly add middleware in our routes like this
Route::get('/home', 'HomeController@index')->middleware('auth');
Or, we can add it in our controller if we want to restrict all functions in that controller.
class MyController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { return view('some_valuable_page'); }