First, define the routes for login in the web.php
file located in the routes/
folder.
use App\Http\Controllers\AuthController;
Route::get('/login', [AuthController::class, 'showLoginForm'])->name('login');
Route::post('/login', [AuthController::class, 'login']);
The get
route shows the login form, while the post
route handles form submission.
Next, create an AuthController
that will handle the login logic.
php artisan make:controller AuthController
In the controller, add the following methods:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function showLoginForm()
{
return view('auth.login');
}
public function login(Request $request)
{
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required',
]);
if (Auth::attempt($credentials)) {
// Authentication passed, redirect to intended route
return redirect()->intended('dashboard');
}
// Authentication failed
return back()->withErrors([
'email' => 'Invalid credentials. Please try again.',
])->withInput();
}
}
This code handles form validation, attempts login with the provided credentials, and redirects on success or failure.
Create a Blade template for the login page inside the resources/views/auth/
folder:
<!-- resources/views/auth/login.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
</head>
<body>
<div class="login-container">
<form method="POST" action="{{ route('login') }}">
@csrf
<h2>Login</h2>
<div class="form-group">
<label for="email">Email Address</label>
<input type="email" name="email" id="email" value="{{ old('email') }}" required autofocus>
@error('email')
<span class="error">{{ $message }}</span>
@enderror
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" id="password" required>
@error('password')
<span class="error">{{ $message }}</span>
@enderror
</div>
<button type="submit">Login</button>
</form>
</div>
</body>
</html>
The login page is simple and includes fields for email and password along with error messages for validation.
Once everything is set up, navigate to /login
to see your login page. Enter valid credentials to ensure that you can successfully log in and be redirected to the dashboard.
@csrf
Blade directive. (without this you cannot make any request in api.In this tutorial, we covered the basics of implementing login functionality in Laravel. By following these steps, you can create a secure and user-friendly login system for your web application.