Key Takeaways
- Laravel provides multiple authentication methods: password-based, token-based, and multi-factor authentication.
- Setting up authentication involves database migrations, route/controller configuration, and view customization.
- Built-in tools and packages like Breeze, Jetstream, Sanctum, and Fortify simplify authentication and improve security.
Imagine needing a secure login system to protect user data, restrict access, and provide a smooth user experience. Laravel login authentication offers flexible methods and built-in packages to implement a robust system without reinventing the wheel. With managed Laravel hosting, like Cloudways, you can further ensure speed, reliability, and scalability for your application.
This guide covers key concepts, implementation steps, and best practices for setting up Laravel login authentication effectively.
Cloudways Performance Bootcamp · Free · Mar 10–11
From CDN to Core Web Vitals, watch experts fix real WordPress performance issues, live.
Why Laravel Login Authentication Matters
Authentication verifies a user’s identity using credentials like email or username and password. Proper authentication ensures:
-
Secure access to sensitive data
-
Restriction of unauthorized users
-
Seamless user experience
Laravel provides ready-to-use authentication packages, making it easier to implement secure login flows while maintaining flexibility for custom requirements.
Different Approaches to Laravel Authentication
When it comes to setting up login authentication in Laravel, there are several methods available that cater to different authentication requirements.
Laravel, being a powerful PHP framework, provides developers with flexibility and options to choose the authentication method that best suits their project’s needs.
Managed Laravel Hosting: Elevate Your Web Experience
Say goodbye to hosting complexities. Cloudways’ managed Laravel hosting takes care of the technicalities, so you can focus on crafting remarkable web experiences.
Let’s explore a couple of the most commonly used Laravel authentication methods.
Password Based Authentication
Password-based authentication is a commonly used method for user authentication, where users verify their identity by providing a username and password. Laravel, being a versatile PHP framework, provides a straightforward way to set up password-based authentication using its built-in features.
To setup password-based authentication, you need to ensure you have Laravel 9 installed on your system. Once you have a Laravel project set up, follow these steps:
- Start by configuring your database connection in the .env file located at the root of your Laravel project.
- Set the appropriate values for DB_CONNECTION, DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, and DB_PASSWORD according to your database setup.
- Run the following command to generate the migration file:
php artisan make:migration create_users_table --create=users
- You can define the necessary fields for the users table, Once you have defined the table structure, run the migration to create the users table
php artisan migrate
- Laravel’s User model represents the users table. Make sure the User model exists in the app/Models directory or the default app directory if you’re using an older Laravel version.
- If it doesn’t exist, you can generate it using the following command
php artisan make:model Models\\User
- open the config/auth.php file and configure the authentication guards and providers. Make sure that the default guard is set to web
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
- Access the registration page by visiting /register on your Laravel application’s URL.
- Visit the login page at /login to log in with the registered user’s credentials. Laravel’s authentication system will handle the verification process and create a session for the authenticated user
Token Based Authentication
Token-based authentication is a popular method for securing APIs and providing stateless authentication. Instead of relying on sessions or cookies, tokens are used to authenticate and authorize API requests.
Laravel 9 offers built-in support for token-based authentication through the Laravel Sanctum package.
Here’s a step-by-step guide to implementing token-based authentication in Laravel:
- Start by installing the Laravel Sanctum package using Composer.
composer require laravel/sanctum
- Next, run the migration to create the necessary tables for Sanctum:
php artisan migrate
- To enable Sanctum, you need to update your app/Http/Kernel.php file. Add the \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class middleware to the $middlewareGroups array:
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
- Generate API Tokens
php artisan sanctum:tokens
- Enable Token Authentication for Users
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
// ...
}
- Authentication Routes and Middleware; To generate these, run the following command:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
This will publish the Sanctum configuration file, migration, and routes. You can find the routes in the routes/api.php file.
- To secure your API routes, you can apply the Sanctum middleware to them.
'auth:sanctum' => \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
- Now you can use the auth:sanctum middleware to protect your API routes.
Multi-Factor Authentication
Multi-factor authentication (MFA) adds an extra layer of security to user authentication by requiring users to provide multiple forms of verification.
This approach significantly enhances the security of user accounts by combining something the user knows with something they possess or something unique to them such as a fingerprint or facial recognition.
Laravel 9 provides built-in support for implementing multi-factor authentication through the Laravel Fortify package.
Here’s a step-by-step guide to setting up multi-factor authentication in Laravel:
- Start by installing the Laravel Fortify package using Composer
composer require laravel/fortify
- Next, run the migration to create the necessary tables for Fortify:
php artisan migrate
- Enable multi-factor authentication:
'features' => [
// ...
'two-factor-authentication' => true,
],
- Make sure the model implements the TwoFactorAuthenticatable contract and imports the Laravel\Fortify\TwoFactorAuthenticatable trait:
use Laravel\Fortify\TwoFactorAuthenticatable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable, TwoFactorAuthenticatable;
// ...
}
- Enable two-factor authentication for users:
'two-factor' => [
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
],
],
- Generate Laravel pre-built views and routes for multi-factor authentication using the following command:
php artisan fortify:two-factor-auth
This command generates the necessary views in the resources/views/auth/two-factor directory and adds the required routes to your routes/web.php file.
- Customize the authentication process, by modifying the views in resources/views/auth/two-factor and the corresponding controllers.
Prerequisites for Laravel 9.X Custom Authentication
- To begin, get your server on Cloudways if you do not have one.
- Launch a Laravel 9.x app.
Step 1: Setup the Database
- Go to your Laravel application on the Cloudways server.
- Click on Launch Database.
- Click on Create Table. Name the new table users and select innoDB and ascii_general
- Add the following columns in the table:
-
- id (int) (Check AutoIncrement A.I.)
- name (text)
- username (text)
- email (text)
- password (text)
- remember_token (text)
- timestamp (time)
- Click Save
- Now Click New Item and then add the following user:
- Name: Cloudways user
- Username: NewUser
- Email: [email protected]
- Password: Start123
- Click Save
Tailor Made Cloud Hosting For Different PHP Frameworks
From Laravel to CodeIgniter, We Have Got You Covered On All PHP Frameworks!
Step 2: Setup the Routes
your-project-root-directory/routes/web.php
Here lies all the endpoints.
Let’s make three endpoints:
- Post Call to submit the form
- Get Call to show the login form
- To LogOut.
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
*/
// route to show the login form
Route::get('login', array(
'uses' => 'MainController@showLogin'
));
// route to process the form
Route::post('login', array(
'uses' => 'MainController@doLogin'
));
Route::get('logout', array(
'uses' => 'MainController@doLogout'
));
Route::get('/',
function ()
{
return view('welcome');
});
Step 3: Make the Controllers
Using the following command to read information from the Request object and creates and returns a Response object.
use App\Http\Controllers\UserController;
Route::get('/user/{id}', [UserController::class, 'show']);
I will extend MainController from the Base Controller and make three functions to show login, check the login and for logging out.
<?php
namespaceAppHttpControllers;
useRedirect;
useAuth;
useInput;
useIlluminateSupportFacadesValidator;
useIlluminateFoundationBusDispatchesJobs;
useIlluminateRoutingController as BaseController;
useIlluminateFoundationValidationValidatesRequests;
useIlluminateFoundationAuthAccessAuthorizesRequests;
useIlluminateFoundationAuthAccessAuthorizesResources;
useIlluminateHtmlHtmlServiceProvider;
class MainController extends BaseController
{
public
function showLogin()
{
// Form View
return view('login');
}
public
function doLogout()
{
Auth::logout(); // logging out user
return Redirect::to('login'); // redirection to login screen
}
public
function doLogin()
{
// Creating Rules for Email and Password
$rules = array(
'email' => 'required|email', // make sure the email is an actual email
'password' => 'required|alphaNum|min:8'
// password has to be greater than 3 characters and can only be alphanumeric and);
// checking all field
$validator = Validator::make(Input::all() , $rules);
// if the validator fails, redirect back to the form
if ($validator->fails())
{
return Redirect::to('login')->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
}
else
{
// create our user data for the authentication
$userdata = array(
'email' => Input::get('email') ,
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($userdata))
{
// validation successful
// do whatever you want on success
}
else
{
// validation not successful, send back to form
return Redirect::to('checklogin');
}
}
}
}
Step 4: Setup the View
Now let’s make the view, which will contain the HTML code of the app.
$ vim resources/views/checklogin.blade.php
The .blade.php extension lets Laravel know that I am using its Blade Templating system.
Here is the HTML code for this file.
<!doctype html>
<html>
<head>
<title>My Login Page</title>
</head>
<body>
<
{{ Form::open(array('url' => 'login')) }}
<h1>Login</h1>
<!-- if there are login errors, show them here -->
<p>
{{ $errors->first('email') }}
{{ $errors->first('password') }}
</p>
<p>
{{ Form::label('email', 'Email Address') }}
{{ Form::text('email', Input::old('email'), array('placeholder' => '[email protected]')) }}
</p>
<p>
{{ Form::label('password', 'Password') }}
{{ Form::password('password') }}
</p>
<p>{{ Form::submit('Submit!') }}</p>
{{ Form::close() }}
Now let’s check how the app looks!

This is a simple example of how you could implement login authentication in a Laravel app.
Another Laravel Login and Registration Setup
Here is a GIF that explains the entire process:

Database Migration
In a Laravel powered app, database configuration is handled by two files: env and config/database.php. In my case, I created a database with the name loginuser. The Cloudways Database Manager makes the entire process very easy.
Next, run the following command in the terminal to create tables in the database:
Login to SSH terminal by using Master Credentials and go to the application folder by using the command
$ ls applications $ cd applications applications$ ls pjbeasusxr trxbnbphae applications$ cd trxbnbphae/ trxbnbphae$ cd public_html/
php artisan migrate
Now, when you check the database, you will see that the tables have been created successfully.
Setup Laravel Login Authentication
php artisan make:auth
This can also be used as for routes for all authentication end-points.
Register

Login

Use Username for Authentication
Laravel uses the the default email address as authentication field. However, users prefer to use their username instead of emails. To change the default behavior, here is how to define a username in the controller.
Login Controller
public function username()
{ return 'username';}
Empower Your Laravel Projects With Cloudways’ Laravel Managed Hosting!
Unleash the Power of Laravel with Managed Hosting – Where Innovation Meets Effortless Excellence!
Conclusion
Setting up Laravel login authentication doesn’t have to be a daunting task. With the right approach and utilizing the powerful features you can implement a strong and secure authentication system for your web application.
Remember to consider your project’s specific needs and security requirements when choosing the authentication method. And if you have any questions, leave them in the comments and I’ll get back to ASAP.
Frequently Asked Questions
Q1: What is authentication in Laravel?
Authentication is the process of verifying a user’s identity using credentials like email/username and password. In web applications, sessions usually handle authentication to maintain a logged-in state.
Q2: How do I get the authenticated user in Laravel?
$user = Auth::user();
$id = Auth::id();
// For APIs:
auth('sanctum')->user(); // or auth('api')->user();
Q3: What is the best authentication method in Laravel?
Web apps: Breeze (simple) or Jetstream (advanced)
APIs: Sanctum for SPAs, Passport for OAuth2
Q4: Does Laravel have default credentials?
No, Laravel does not ship with default credentials. Admin panels like Laravel-Admin may use admin/admin locally, but these should always be changed for security.
Q5: How do I install authentication in Laravel?
composer require laravel/ui
php artisan ui vue --auth
php artisan migrate
After installation, access login and registration pages at /login and /register.
Q6: What authentication methods does Laravel support?
- Session-based authentication (web apps)
- Token-based authentication (APIs)
- Social login via Laravel Socialite (Google, Facebook, GitHub, etc.)
Q7: Can I customize login and registration in Laravel?
Yes. You can modify the generated views, controllers, and routes, or implement custom guards and logic in auth.php.
Q8: How do I implement social login?
Use Laravel Socialite for OAuth authentication with popular platforms like Google, Facebook, Twitter, and GitHub.
Q9: How do I authenticate a login manually?
Use the Auth::attempt() method:
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed
}
Pre-built scaffolding via Breeze or Jetstream can simplify this.
Q10: How do I set authorization in Laravel?
Create policies:
php artisan make:policy PolicyName
Then enforce in controllers or routes using Gate::allows() or $this->authorize().
Q11: How do I create admin authentication?
- Add an
is_admincolumn to the users table. - Update middleware to check this column.
- Separate admin and user routes using route groups.
Q12: How do I create custom authentication?
- Build custom login/registration forms.
- Handle requests in controllers.
- Define custom guards in
auth.phpand useAuth::guard().
Q13: How do I log in using Laravel?
Submit credentials to the login route. Laravel uses Auth::attempt() to authenticate the user.
Q14: How do I write logs in Laravel?
Use Laravel’s logging helper:
Log::info('Your message');
Logs are stored in storage/logs/laravel.log.
Q15: How do I access Laravel admin?
Typically, admin login pages are at /admin/login. Authenticate using admin credentials to access the dashboard.
Q16: Which controller handles login in Laravel?
LoginController located in App\Http\Controllers\Auth manages login functionality in Laravel’s default setup.
Shahzeb Ahmed
Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]