Getting Started with Laravel 11
Learn the basics of Laravel 11 and start building modern web applications.

# Getting Started with Laravel 11: A Complete Beginner's Guide
Laravel continues to be one of the most popular PHP frameworks, and with the release of Laravel 11, developers have even more powerful tools at their disposal. Whether you're new to Laravel or upgrading from a previous version, this guide will walk you through everything you need to know to get started with Laravel 11.
## What's New in Laravel 11?
Laravel 11 introduces several exciting features and improvements that make development even more enjoyable:
- **Streamlined Application Structure**: A cleaner, more minimal application skeleton
- **Per-second Rate Limiting**: More granular control over API rate limiting
- **Health Routing**: Built-in health check endpoints for your applications
- **Eager Load Limit**: Better performance when eager loading relationships
- **New Artisan Commands**: Additional helpful commands for development
- **PHP 8.2+ Requirement**: Taking advantage of the latest PHP features
## Prerequisites
Before diving into Laravel 11, make sure you have the following installed on your system:
- **PHP 8.2 or higher** with required extensions (OpenSSL, PDO, Mbstring, Tokenizer, XML, Ctype, JSON, BCMath)
- **Composer** (PHP dependency manager)
- **Node.js and NPM** (for frontend asset compilation)
- **A database system** (MySQL, PostgreSQL, SQLite, or SQL Server)
- **A code editor** (VS Code, PhpStorm, or your preferred editor)
## Installation Methods
### Method 1: Using Laravel Installer (Recommended)
The Laravel installer is the fastest way to create new Laravel projects:
```bash
# Install the Laravel installer globally
composer global require laravel/installer
# Create a new Laravel 11 project
laravel new my-laravel-app
# Navigate to your project
cd my-laravel-app
```
### Method 2: Using Composer Create-Project
If you prefer using Composer directly:
```bash
# Create a new Laravel project
composer create-project laravel/laravel my-laravel-app
# Navigate to your project
cd my-laravel-app
```
## Initial Configuration
### Environment Setup
Laravel uses environment variables for configuration. Copy the example environment file and configure it for your local setup:
```bash
# Copy the environment file
cp .env.example .env
# Generate an application key
php artisan key:generate
```
### Database Configuration
Open your `.env` file and configure your database connection:
```env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_laravel_app
DB_USERNAME=your_username
DB_PASSWORD=your_password
```
For quick development, you can also use SQLite:
```env
DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite
```
## Starting Your Development Server
Laravel 11 comes with Artisan, a powerful command-line tool. Start your development server with:
```bash
php artisan serve
```
Your application will be available at `http://localhost:8000`.
## Understanding Laravel's Structure
Laravel 11 features a streamlined directory structure. Here are the key directories you'll work with:
```
my-laravel-app/
├── app/
│ ├── Http/Controllers/ # Your application controllers
│ ├── Models/ # Eloquent models
│ └── Providers/ # Service providers
├── bootstrap/ # Framework bootstrap files
├── config/ # Configuration files
├── database/
│ ├── migrations/ # Database migrations
│ └── seeders/ # Database seeders
├── public/ # Web server document root
├── resources/
│ ├── css/ # CSS files
│ ├── js/ # JavaScript files
│ └── views/ # Blade templates
├── routes/
│ ├── web.php # Web routes
│ └── api.php # API routes
├── storage/ # Logs, cache, uploads
└── tests/ # Application tests
```
## Creating Your First Route
Routes define how your application responds to different URLs. Open `routes/web.php` and add a simple route:
```php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('/hello', function () {
return '<h1>Hello, Laravel 11!</h1>';
});
Route::get('/user/{name}', function ($name) {
return "Hello, " . $name . "!";
});
```
## Creating Your First Controller
Controllers help organize your application logic. Create a controller using Artisan:
```bash
php artisan make:controller HomeController
```
This creates `app/Http/Controllers/HomeController.php`. Edit it to add some methods:
```php
<?php
namespace App\Http\Controllers;
class HomeController extends Controller
{
public function index()
{
return view('home');
}
public function about()
{
$data = [
'title' => 'About Us',
'description' => 'This is our about page.'
];
return view('about', $data);
}
}
```
Update your routes to use the controller:
```php
use App\Http\Controllers\HomeController;
Route::get('/home', [HomeController::class, 'index']);
Route::get('/about', [HomeController::class, 'about']);
```
## Working with Views and Blade Templates
Laravel uses the Blade templating engine. Create a layout file at `resources/views/layouts/app.blade.php`:
```php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ $title ?? 'Laravel 11 App' }}</title>
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body>
<nav class="navbar">
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
<main>
@yield('content')
</main>
</body>
</html>
```
Create a home view at `resources/views/home.blade.php`:
```php
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Welcome to Laravel 11!</h1>
<p>This is your home page.</p>
</div>
@endsection
```
## Database Migrations and Models
Laravel's migration system helps you manage your database schema. Create a migration for a blog post model:
```bash
php artisan make:migration create_posts_table
```
Edit the migration file in `database/migrations/`:
```php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->string('slug')->unique();
$table->boolean('published')->default(false);
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('posts');
}
};
```
Run the migration:
```bash
php artisan migrate
```
Create an Eloquent model:
```bash
php artisan make:model Post
```
Edit `app/Models/Post.php`:
```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title',
'content',
'slug',
'published'
];
protected $casts = [
'published' => 'boolean',
];
}
```
## Frontend Asset Compilation with Vite
Laravel 11 uses Vite for fast frontend asset compilation. Your assets are defined in `vite.config.js`:
```javascript
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel({
input: ['resources/css/app.css', 'resources/js/app.js'],
refresh: true,
}),
],
});
```
Install NPM dependencies and start the development server:
```bash
npm install
npm run dev
```
For production builds:
```bash
npm run build
```
## Essential Artisan Commands
Here are some Artisan commands you'll use frequently:
```bash
# Generate application key
php artisan key:generate
# Run migrations
php artisan migrate
# Rollback migrations
php artisan migrate:rollback
# Create a new controller
php artisan make:controller PostController
# Create a new model with migration
php artisan make:model Post -m
# Create a new seeder
php artisan make:seeder PostSeeder
# Run database seeders
php artisan db:seed
# Clear application cache
php artisan cache:clear
# Clear configuration cache
php artisan config:clear
# List all routes
php artisan route:list
```
## Best Practices for Laravel 11
As you begin your Laravel journey, keep these best practices in mind:
1. **Follow PSR Standards**: Use proper PHP coding standards and naming conventions
2. **Use Eloquent Relationships**: Leverage Laravel's powerful ORM for database relationships
3. **Implement Form Requests**: Use form request validation for clean, reusable validation logic
4. **Utilize Service Containers**: Take advantage of Laravel's dependency injection container
5. **Write Tests**: Use Laravel's built-in testing tools to ensure code quality
6. **Keep Controllers Thin**: Move business logic to service classes or models
7. **Use Middleware**: Implement middleware for cross-cutting concerns like authentication
8. **Cache Strategically**: Implement caching where appropriate for better performance
## Next Steps
Now that you have Laravel 11 set up and understand the basics, here are some areas to explore next:
- **Authentication**: Implement user registration and login using Laravel Breeze or Jetstream
- **API Development**: Build RESTful APIs using Laravel's API resources
- **Testing**: Write feature and unit tests using PHPUnit
- **Package Development**: Create reusable packages for your applications
- **Deployment**: Learn how to deploy Laravel applications to production servers
- **Advanced Features**: Explore queues, events, broadcasting, and other advanced Laravel features
## Conclusion
Laravel 11 provides an excellent foundation for building modern web applications. With its elegant syntax, powerful features, and comprehensive ecosystem, Laravel continues to be a top choice for PHP developers worldwide.
The framework's emphasis on developer experience, combined with its robust feature set, makes it perfect for both beginners and experienced developers. As you continue your Laravel journey, remember that the Laravel community is incredibly welcoming and helpful, so don't hesitate to engage with the community through forums, Discord, and social media.
Start building something amazing with Laravel 11 today, and enjoy the elegant development experience that has made Laravel one of the most beloved PHP frameworks in the world!