How to Setup Laravel Authentication in Few Simple Steps
How to Setup Laravel Authentication in Few Simple Steps
Learn how to quickly set up authentication in your Laravel application using Laravel's built-in authentication features.
Introduction
Laravel provides a robust authentication system out of the box. This guide will show you how to set up authentication quickly and efficiently using Laravel's built-in features.
Prerequisites
- Laravel 6.x or higher
- Database configured
- Basic understanding of Laravel
1 Install Laravel UI Package
Install the Laravel UI package via Composer:
composer require laravel/ui
Generate the authentication scaffolding:
php artisan ui bootstrap --auth
npm install && npm run dev
2 Configure Database
Update your `.env` file with database credentials:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password
Run migrations to create the users table:
php artisan migrate
3 Configure Routes
Add authentication routes in `routes/web.php`:
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
4 Configure User Model
Update your `app/Models/User.php`:
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
5 Configure Authentication Controller
Update your `app/Http/Controllers/Auth/LoginController.php`:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
6 Add Authentication Middleware
Protect routes in `routes/web.php`:
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', function () {
return view('dashboard');
});
});
7 Customize Views
Views are located in `resources/views/auth/`. You can customize:
- login.blade.php
- register.blade.php
- forgot-password.blade.php
- reset-password.blade.php
- verify-email.blade.php
Key Features Covered
- User registration
- Login/logout
- Password reset
- Email verification
- Remember me functionality
- Route protection
Best Practices
- Use strong password validation
- Implement rate limiting
- Enable CSRF protection
- Use secure session handling
- Implement proper error handling
Common Issues
- Missing database configuration
- Incorrect route definitions
- Missing middleware
- Session configuration issues
- Mail configuration problems