This logs out the current user and sends them to the login page.
Laravel
<?php
// Logging out a user
Auth::logout();
return redirect('/login');
This sends the user to the page they wanted before login, or to the dashboard if none.
Laravel
<?php
// Redirect after login
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return redirect()->intended('dashboard');
}
Sample Program
This controller handles showing the login form, logging in users by checking their email and password, and logging them out safely by clearing their session.
Laravel
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
class AuthController extends Controller
{
public function showLoginForm()
{
return view('login');
}
public function login(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect()->intended('dashboard');
}
return back()->withErrors([
'email' => 'The provided credentials do not match our records.',
]);
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/login');
}
}
OutputSuccess
Important Notes
Always validate user input before trying to log in.
Regenerate the session after login to prevent security issues.
Invalidate and regenerate the session token on logout to keep sessions safe.
Summary
Login checks user email and password to allow access.
Logout ends the user session and protects their account.
Laravel's Auth facade makes login and logout easy and secure.
Practice
(1/5)
1. What does the Auth::attempt() method do in Laravel's login process?
easy
A. It registers a new user in the database.
B. It logs out the user and clears the session.
C. It checks user credentials and starts a session if valid.
D. It sends a password reset email to the user.
Solution
Step 1: Understand Auth::attempt() purpose
This method tries to verify the user's email and password against stored data.
Step 2: Recognize session start on success
If credentials are correct, Laravel starts a session to keep the user logged in.
Final Answer:
It checks user credentials and starts a session if valid. -> Option C