Laravel provides powerful tools for authentication and authorization, allowing you to build secure applications efficiently.
Create Authentication Controllers
php artisan make:controller Auth/RegisterController
php artisan make:controller Auth/LoginController
php artisan make:controller Auth/ForgotPasswordController
php artisan make:controller Auth/ResetPasswordController
Define Routes in routes/web.php
, add routes for authentication:
// Authentication Routes
Route::get('login', [LoginController::class, 'showLoginForm'])->name('login');
Route::post('login', [LoginController::class, 'login']);
Route::post('logout', [LoginController::class, 'logout'])->name('logout');
// Registration Routes
Route::get('register', [RegisterController::class, 'showRegistrationForm'])->name('register');
Route::post('register', [RegisterController::class, 'register']);
// Password Reset Routes
Route::get('password/reset', [ForgotPasswordController::class, 'showLinkRequestForm'])->name('password.request');
Route::post('password/email', [ForgotPasswordController::class, 'sendResetLinkEmail'])->name('password.email');
Route::get('password/reset/{token}', [ResetPasswordController::class, 'showResetForm'])->name('password.reset');
Route::post('password/reset', [ResetPasswordController::class, 'reset'])->name('password.update');
Create Views
Create Blade views for login, registration, and password reset in resources/views/auth
:
login.blade.php
register.blade.php
passwords/email.blade.php
passwords/reset.blade.php
These views should contain HTML forms corresponding to each action.
Implement Controllers
In your controllers, implement the methods to handle authentication. For instance, in LoginController
:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function showLoginForm()
{
return view('auth.login');
}
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect()->intended('home');
}
return redirect('login')->withErrors(['email' => 'Invalid credentials']);
}
public function logout()
{
Auth::logout();
return redirect('/');
}
}
Similarly, implement methods in RegisterController
, ForgotPasswordController
, and ResetPasswordController
.
Update User Model
Ensure your User
model (typically located in app/Models/User.php
) implements Illuminate\Contracts\Auth\Authenticatable
and Illuminate\Auth\MustVerifyEmail
if using email verification.
Implementing Authorization
Authorization determines what authenticated users can do. Laravel offers Gates and Policies for this purpose.
Using Gates
Gates are used for simple authorization checks. Define gates in AuthServiceProvider
:
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
public function boot()
{
$this->registerPolicies();
Gate::define('view-dashboard', function ($user) {
return $user->is_admin;
});
}
}
Use this gate in your controllers or Blade views:
if (Gate::allows('view-dashboard')) {
// User can view the dashboard
}
In Blade:
@can('view-dashboard')
<!-- User can view the dashboard -->
@endcan
Using Policies
Policies are ideal for managing authorization logic related to a specific model. Create a policy using Artisan:
php artisan make:policy PostPolicy
This will create a policy file in app/Policies
. Define policy methods like so:
namespace App\Policies;
use App\Models\Post;
use App\Models\User;
class PostPolicy
{
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
}
Register the policy in AuthServiceProvider
:
protected $policies = [
\App\Models\Post::class => \App\Policies\PostPolicy::class,
];
Use the policy methods in your controllers:
public function update(Post $post)
{
$this->authorize('update', $post);
// Update logic here
}
In Blade:
@can('update', $post)
<!-- User can update the post -->
@endcan
Testing Authentication and Authorization
Testing ensures your authentication and authorization systems work as expected. Use Laravel’s built-in testing tools.
Testing Authentication
public function testUserCanLogin()
{
$user = User::factory()->create([
'password' => bcrypt('password'),
]);
$response = $this->post('/login', [
'email' => $user->email,
'password' => 'password',
]);
$response->assertRedirect('/home');
}
Testing Authorization
public function testUserCannotAccessRestrictedPage()
{
$user = User::factory()->create(['is_admin' => false]);
$response = $this->actingAs($user)->get('/admin');
$response->assertStatus(403); // Forbidden
}
Conclusion
Implementing authentication and authorization manually in Laravel provides flexibility and control over how these features are integrated into your application. By following this guide, you can create a secure authentication system and manage user permissions effectively, tailored to your specific needs.