Getting Started with Laravel: A Beginner's Guide
Laravel has revolutionized PHP development, transforming it from a language often criticized for its inconsistencies into a powerful ecosystem for building modern web applications. Whether you're a PHP developer looking to level up your skills or a newcomer to backend development, this comprehensive guide will walk you through everything you need to know to get started with Laravel.
Laravel is the most starred PHP framework on GitHub with over 75,000 stars. It's used by companies like Disney, BBC, Pfizer, and thousands of startups worldwide. Its elegant syntax and robust features make it the go-to choice for modern PHP development.
What is Laravel?
Laravel is a free, open-source PHP web framework created by Taylor Otwell in 2011. It follows the Model-View-Controller (MVC) architectural pattern and provides an expressive, elegant syntax that makes web development enjoyable and creative.
Here's what makes Laravel stand out:
- Elegant Syntax: Laravel's clean, readable code makes development a pleasure
- Robust Ecosystem: Tools like Forge, Vapor, Nova, and Horizon extend Laravel's capabilities
- Active Community: Extensive documentation, tutorials, and community support
- Built-in Features: Authentication, routing, sessions, caching, and more out of the box
- Eloquent ORM: Beautiful, intuitive database interactions
Laravel's MVC Architecture Flow
Prerequisites and Installation
Before diving into Laravel, make sure you have the following installed on your system:
| Requirement | Minimum Version | Recommended |
|---|---|---|
| PHP | 8.1 | 8.2+ |
| Composer | 2.0 | Latest |
| Node.js | 16.x | 18.x+ |
| Database | MySQL 5.7 / PostgreSQL 10 | MySQL 8.0 / PostgreSQL 15 |
Step-by-Step Installation
Install Composer
Composer is PHP's dependency manager. Download it from getcomposer.org or use your system's package manager.
Create New Laravel Project
Use the Laravel installer or Composer to create a fresh Laravel application.
# Install Laravel installer globally
composer global require laravel/installer
# Create a new Laravel project
laravel new my-awesome-app
# OR use Composer directly
composer create-project laravel/laravel my-awesome-app
# Navigate to project directory
cd my-awesome-app
# Start the development server
php artisan serve
Configure Environment
Copy .env.example to .env and configure your database credentials.
Generate Application Key
Run php artisan key:generate to set your APP_KEY in the .env file.
If you're using Laravel Sail, you can spin up a complete development environment with Docker using just ./vendor/bin/sail up. This includes PHP, MySQL, Redis, and more!
Understanding Laravel's Directory Structure
Laravel's directory structure is designed to be intuitive and organized. Here's what each main directory contains:
Routing Basics
Routes are the entry point to your Laravel application. They define how your application responds to HTTP requests.
Define routes in routes/web.php:
use Illuminate\Support\Facades\Route;
// Basic GET route
Route::get('/', function () {
return view('welcome');
});
// Route to a controller
Route::get('/users', [UserController::class, 'index']);
// Different HTTP methods
Route::post('/users', [UserController::class, 'store']);
Route::put('/users/{id}', [UserController::class, 'update']);
Route::delete('/users/{id}', [UserController::class, 'destroy']);
Capture dynamic segments from the URL:
// Required parameter
Route::get('/user/{id}', function ($id) {
return "User ID: " . $id;
});
// Optional parameter with default
Route::get('/user/{name?}', function ($name = 'Guest') {
return "Hello, " . $name;
});
// Multiple parameters
Route::get('/posts/{post}/comments/{comment}', function ($postId, $commentId) {
return "Post: $postId, Comment: $commentId";
});
// Regex constraints
Route::get('/user/{id}', function ($id) {
return "User: " . $id;
})->where('id', '[0-9]+');
Name your routes for easy URL generation:
// Define named route
Route::get('/user/profile', [ProfileController::class, 'show'])
->name('profile');
// Generate URL to named route
$url = route('profile');
// Redirect to named route
return redirect()->route('profile');
// In Blade templates
<a href="{{ route('profile') }}">Profile</a>
// With parameters
Route::get('/user/{id}/profile', [ProfileController::class, 'show'])
->name('profile');
$url = route('profile', ['id' => 1]);
Group routes with shared attributes:
// Middleware group
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
Route::get('/settings', [SettingsController::class, 'index']);
});
// Prefix group
Route::prefix('admin')->group(function () {
Route::get('/users', [AdminUserController::class, 'index']);
// URL: /admin/users
});
// Combined attributes
Route::prefix('api')
->middleware('api')
->name('api.')
->group(function () {
Route::get('/users', [ApiUserController::class, 'index'])
->name('users.index');
// Name: api.users.index
});
Controllers
Controllers group related request handling logic into single classes. They serve as the middleman between your routes and your application's business logic.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Display a listing of users.
*/
public function index()
{
$users = User::all();
return view('users.index', compact('users'));
}
/**
* Show the form for creating a new user.
*/
public function create()
{
return view('users.create');
}
/**
* Store a newly created user.
*/
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|min:8|confirmed',
]);
$user = User::create([
'name' => $validated['name'],
'email' => $validated['email'],
'password' => bcrypt($validated['password']),
]);
return redirect()
->route('users.show', $user)
->with('success', 'User created successfully!');
}
/**
* Display the specified user.
*/
public function show(User $user)
{
return view('users.show', compact('user'));
}
}
Generate controllers quickly with Artisan: php artisan make:controller UserController --resource creates a controller with all CRUD methods pre-defined!
Eloquent ORM: Working with Databases
Eloquent is Laravel's powerful ORM (Object-Relational Mapping) that makes database interactions a breeze. Each database table has a corresponding Model that you use to interact with that table.
How Eloquent processes database queries
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class User extends Model
{
use HasFactory;
// Mass assignable attributes
protected $fillable = [
'name',
'email',
'password',
];
// Hidden from arrays/JSON
protected $hidden = [
'password',
'remember_token',
];
// Attribute casting
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
// Relationship: User has many posts
public function posts()
{
return $this->hasMany(Post::class);
}
// Relationship: User belongs to many roles
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
Common Eloquent Operations
// Retrieve all users
$users = User::all();
// Find by primary key
$user = User::find(1);
$user = User::findOrFail(1); // Throws 404 if not found
// Query with conditions
$activeUsers = User::where('status', 'active')
->where('age', '>', 18)
->orderBy('created_at', 'desc')
->get();
// First matching record
$admin = User::where('role', 'admin')->first();
// Create new record
$user = User::create([
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => bcrypt('password'),
]);
// Update existing record
$user->update(['name' => 'Jane Doe']);
// Delete record
$user->delete();
// Soft delete (if enabled)
$user->delete(); // Marks as deleted
User::withTrashed()->get(); // Include soft deleted
// Eager loading relationships
$users = User::with(['posts', 'roles'])->get();
// Pagination
$users = User::paginate(15);
Blade Templates
Blade is Laravel's powerful templating engine that makes writing views elegant and efficient. It provides convenient shortcuts for common PHP control structures while being compiled into plain PHP code for optimal performance.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>@yield('title', 'My Laravel App')</title>
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body>
<nav>
@include('partials.navigation')
</nav>
<main>
@yield('content')
</main>
<footer>
@include('partials.footer')
</footer>
</body>
</html>
@extends('layouts.app')
@section('title', 'All Users')
@section('content')
<h1>Users</h1>
{{-- Display success message --}}
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
{{-- Loop through users --}}
@forelse($users as $user)
<div class="user-card">
<h2>{{ $user->name }}</h2>
<p>{{ $user->email }}</p>
@if($user->isAdmin())
<span class="badge">Admin</span>
@endif
<a href="{{ route('users.show', $user) }}">
View Profile
</a>
</div>
@empty
<p>No users found.</p>
@endforelse
{{-- Pagination links --}}
{{ $users->links() }}
@endsection
Blade Directives Quick Reference
| Directive | Purpose | Example |
|---|---|---|
{{ $var }} |
Echo escaped content | {{ $user->name }} |
{!! $var !!} |
Echo unescaped HTML | {!! $post->content !!} |
@if / @else |
Conditional statements | @if($user) ... @endif |
@foreach |
Loop through arrays | @foreach($items as $item) |
@forelse |
Loop with empty fallback | @forelse ... @empty ... @endforelse |
@auth / @guest |
Auth conditionals | @auth Welcome! @endauth |
@csrf |
CSRF token field | <form>@csrf</form> |
@method |
Form method spoofing | @method('PUT') |
Form Validation
Laravel provides several different approaches to validate incoming data. The most common method is using the validate method available on all incoming HTTP requests.
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required|string|max:255',
'email' => 'required|email|unique:users,email',
'body' => 'required|min:10',
'category_id' => 'required|exists:categories,id',
'tags' => 'array',
'tags.*' => 'exists:tags,id',
'publish_date' => 'nullable|date|after:today',
'image' => 'nullable|image|mimes:jpg,png|max:2048',
]);
// If validation fails, Laravel automatically redirects back
// with errors. If it passes, continue with validated data.
Post::create($validated);
return redirect()->route('posts.index')
->with('success', 'Post created successfully!');
}
Always validate user input! Never trust data from the client. Laravel's validation rules protect against common attacks and ensure data integrity.
Authentication Made Easy
Laravel makes implementing authentication incredibly simple. With Laravel Breeze or Jetstream, you can have a complete authentication system in minutes.
# Install Laravel Breeze
composer require laravel/breeze --dev
# Install Breeze scaffolding
php artisan breeze:install
# Choose your stack:
# - blade (Traditional server-side)
# - react (React with Inertia)
# - vue (Vue with Inertia)
# - api (API only)
# Install dependencies and build assets
npm install && npm run dev
# Run migrations
php artisan migrate
This gives you complete registration, login, password reset, email verification, and password confirmation features out of the box!
Essential Artisan Commands
Artisan is Laravel's command-line interface. It provides numerous helpful commands for development. Here are the most commonly used ones:
| Command | Description |
|---|---|
php artisan serve |
Start development server |
php artisan make:model Post -mcr |
Create model with migration, controller, and resource |
php artisan migrate |
Run database migrations |
php artisan migrate:fresh --seed |
Fresh migration with seeders |
php artisan db:seed |
Run database seeders |
php artisan tinker |
Interactive REPL for Laravel |
php artisan route:list |
List all registered routes |
php artisan cache:clear |
Clear application cache |
php artisan config:clear |
Clear configuration cache |
php artisan optimize |
Cache config, routes, and views |
Next Steps
Congratulations! You now have a solid foundation in Laravel. Here's what to explore next:
Continue Learning
- Middleware: Learn to filter HTTP requests (authentication, logging, CORS)
- API Development: Build RESTful APIs with Laravel Sanctum
- Queues & Jobs: Handle time-consuming tasks asynchronously
- Events & Listeners: Decouple your application logic
- Testing: Write feature and unit tests with PHPUnit
- Deployment: Deploy to production with Laravel Forge or Vapor
Official Documentation: laravel.com/docs
Laracasts: laracasts.com (video tutorials)
Laravel News: laravel-news.com
Laravel Daily: laraveldaily.com
"Laravel has everything you need to build modern web applications. Start simple, and as you grow, Laravel grows with you."
β Taylor Otwell, Creator of Laravel
Laravel is more than just a frameworkβit's an ecosystem designed to make you a more productive developer. With its elegant syntax, powerful features, and vibrant community, you're now equipped to build amazing web applications. Happy coding! π
