Authentication in laravel is really easy and simple to handle. It is important for application to have authentication for security reasons. If you want to configure authentication service then you can edit config/auth.php
file. Here in this document, we will discuss about how to create laravel authentication system.
First of all, lets install laravel/ui
before starting this tutorial. You can install the package by using the command below:
composer require laravel/ui
php artisan ui vue --auth
laravel/ui
aids in developing scaffold for routes and views quickly. In this example, we have scaffold the project with Vue but other components like react, bootstrap can also be done.
After the completion of above process, install npm dependencies to your project by running command below:
npm install
After installation, run npm run dev
to compile assets:
npm run dev
Authentication Testing
Now lets check if authentication is successfully installed in our project or not. For this, we will check login and registration section.
myproject.com/login
myproject.com/register
Restrict Routes
After authentication testing, we will see how to restrict routes for unauthenticated users.
Route::get('dashboard', 'UserController@dashboard')->middleware('auth');
Alternatively, we can also write code in controller’s constructor method:
<?php
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function dashboard(){
//
}
}
Both methods function in same way even if they are in different format. In laravel, we can also check if user is authenticated or not and also get authenticated user’s data.
if(auth()->check()){
// If the user only authenticated
}
$user = auth()->user(); // get authenticated user's data
Path Customization
By default, user is directed towards /home URI if he/she is successfully authenticated. User can configure default path according to their wish in RouteServiceProvider
:
public const HOME = '/profile';
If user needs powerful customization of response then there is authenticated(Request $request, $user)
. This can be found inside AuthenticatesUsers
trait. Users can define authenticated method inside LoginController
:
/**
* The user has been authenticated.
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
protected function authenticated(Request $request, $user)
{
return response([
//
]);
}
Username Customization
For authentication, laravel uses email field by default. If user wants to customize then he/she can change it to username later on.
public function username()
{
return 'username';
}
Similarly, user can also customize other various components like storage, guard and so on. For additional information, users can look into laravel documentation.
Hope you like this tutorial 🙂 be sure to check our other tutorials as well.