ItSolutionStuff.com

Laravel Login with Username or Email Example

By Hardik Savani • November 5, 2023
Laravel

Today, we will learn how to allow login with username or email in laravel 5 application. If you see on some website, they allow email or username both for login or email, username, mobile no, id etc. i mean they provide several way for login.

In this example, you can learn how to make it possible to username or email for login in php laravel 5. we have to simply use PHP filter "FILTER_VALIDATE_EMAIL" to validate is it username or email So, basically you have to write your login method like as bellow i gave you example:

Let's see bellow example and put it on your login method.

Login:

public function login(Request $request)

{

$field = filter_var($request->usernameOrEmail, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

$request->merge([$field => $request->usernameOrEmail]);


if (auth()->attempt($request->only($field, 'password')))

{

return redirect('/');

}


return redirect('login')->withErrors([

'error' => 'These credentials do not match our records.',

]);

}

As you can see above code, it is very simple and we can use it simply. So, use it.

I hope it can help you...

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Model Disable Primary Key & Auto Increment Example

Read Now →

Laravel Carbon Time Format AM PM Example Code

Read Now →

Laravel Sum Query with Where Condition Example

Read Now →

Laravel Seeder from CSV File Example

Read Now →

Laravel Eloquent Select Single Column to Array Example

Read Now →

How to Image Upload in Laravel Vapor?

Read Now →

Laravel One to Many Eloquent Relationship Tutorial

Read Now →

Laravel Many to Many Eloquent Relationship Tutorial

Read Now →

How to Return JSON Response in Laravel?

Read Now →

Laravel 5 manual pagination with array example

Read Now →

How to Resolve Laravel Blank Page on Server?

Read Now →

Laravel XSS Protection Middleware Example

Read Now →

Laravel Join with Subquery in Query Builder Example

Read Now →

How to Create Custom Helper Function in Laravel?

Read Now →

How to Send Mail using Gmail SMTP in Laravel?

Read Now →