0
0
LaravelHow-ToBeginner · 4 min read

How to Create Login in Laravel: Simple Authentication Setup

To create login in Laravel, use the built-in authentication scaffolding by running php artisan make:auth (Laravel 7 or older) or install Laravel Breeze or Jetstream for Laravel 8+. Then configure routes and views to handle user login with Auth::routes() and auth middleware.
📐

Syntax

Laravel provides authentication routes and controllers to handle login. The main parts are:

  • Auth::routes(): Registers all authentication routes like login, register, logout.
  • auth middleware: Protects routes so only logged-in users can access.
  • LoginController: Handles login logic and redirects.
php
<?php
// In routes/web.php
use Illuminate\Support\Facades\Auth;

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->middleware('auth');
💻

Example

This example shows how to set up login routes and protect a page so only logged-in users can see it.

php
<?php
// routes/web.php
use Illuminate\Support\Facades\Auth;

Auth::routes();

Route::get('/', function () {
    return view('welcome');
});

Route::get('/dashboard', function () {
    return 'Welcome to your dashboard!';
})->middleware('auth');
Output
When visiting /dashboard without login, Laravel redirects to /login. After login, /dashboard shows 'Welcome to your dashboard!'
⚠️

Common Pitfalls

Common mistakes include:

  • Not running migrations to create users table before login.
  • Forgetting to add Auth::routes() so login routes don't exist.
  • Not protecting routes with auth middleware, allowing access without login.
  • Using legacy php artisan make:auth in Laravel 8+ without installing Breeze or Jetstream.
php
<?php
// Wrong: Missing Auth::routes()
Route::get('/dashboard', function () {
    return 'Dashboard';
})->middleware('auth');

// Right: Add Auth::routes() to enable login routes
use Illuminate\Support\Facades\Auth;

Auth::routes();
Route::get('/dashboard', function () {
    return 'Dashboard';
})->middleware('auth');
📊

Quick Reference

Command/CodePurpose
php artisan migrateCreate users table for authentication
Auth::routes()Register login, register, logout routes
middleware('auth')Protect routes to require login
php artisan breeze:installInstall simple auth scaffolding (Laravel 8+)
php artisan jetstream:installInstall advanced auth scaffolding (Laravel 8+)

Key Takeaways

Use Laravel's built-in authentication routes with Auth::routes() for quick login setup.
Protect pages by applying the auth middleware to routes.
Run migrations to create the users table before using login features.
For Laravel 8 and newer, use Breeze or Jetstream packages instead of make:auth.
Always test login flow by visiting protected routes to confirm redirection works.