Try Live
Add Docs
Rankings
Pricing
Docs
Install
Theme
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Laravel
https://github.com/laravel/docs
Admin
The Laravel documentation.
Tokens:
812,118
Snippets:
5,492
Trust Score:
9.5
Update:
4 days ago
Context
Skills
Chat
Benchmark
82
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Laravel 13 Documentation ## Introduction Laravel is a powerful PHP web application framework designed with an elegant, expressive syntax that makes web development enjoyable and creative. It provides a comprehensive ecosystem for building modern web applications, offering robust solutions for common development challenges including routing, database management, authentication, queuing, real-time events, and API development. Laravel 13 introduces groundbreaking features like the AI SDK for integrating with artificial intelligence providers, JSON:API resources for standardized API responses, semantic/vector search capabilities, and enhanced PHP attribute support throughout the framework. The framework follows the MVC (Model-View-Controller) architectural pattern while providing additional abstractions for complex functionality. Laravel's philosophy emphasizes developer experience through features like Eloquent ORM for intuitive database interactions, Blade templating for clean view logic, Artisan CLI for code generation and task automation, and a unified API across multiple backend services. Whether building a simple API, a full-stack application, or a complex enterprise system, Laravel provides the tools and conventions needed to develop maintainable, scalable applications. --- ## API Reference ### Routing Laravel's routing system provides a simple, expressive way to define application routes. Routes are defined in `routes/web.php` for web routes and `routes/api.php` for API routes. ```php use Illuminate\Support\Facades\Route; // Basic GET route Route::get('/greeting', function () { return 'Hello World'; }); // Route with parameters Route::get('/user/{id}', function (string $id) { return 'User '.$id; }); // Route with optional parameter and default value Route::get('/user/{name?}', function (?string $name = 'John') { return $name; }); // Named route Route::get('/user/profile', [UserProfileController::class, 'show'])->name('profile'); // Route group with middleware and prefix Route::middleware(['auth'])->prefix('admin')->group(function () { Route::get('/dashboard', [AdminController::class, 'dashboard']); Route::get('/users', [AdminController::class, 'users']); }); // Resource controller routes (creates index, create, store, show, edit, update, destroy) Route::resource('photos', PhotoController::class); // API resource routes (excludes create and edit) Route::apiResource('photos', PhotoController::class); ``` ### Eloquent ORM Eloquent is Laravel's ActiveRecord implementation for database interactions. Each database table has a corresponding Model for interacting with that table. ```php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Flight extends Model { use SoftDeletes; protected $fillable = ['name', 'airline', 'destination']; protected $casts = [ 'arrived_at' => 'datetime', 'options' => 'array', ]; // Define relationship public function passengers() { return $this->hasMany(Passenger::class); } } // Retrieving records $flights = Flight::all(); $flight = Flight::find(1); $flight = Flight::where('active', 1)->first(); $flights = Flight::where('destination', 'Paris')->orderBy('name')->get(); // Creating records $flight = Flight::create([ 'name' => 'Flight 10', 'airline' => 'Air Laravel', ]); // Updating records $flight = Flight::find(1); $flight->name = 'New Flight Name'; $flight->save(); // Mass update Flight::where('active', 1)->update(['delayed' => true]); // Deleting records $flight->delete(); Flight::destroy([1, 2, 3]); // Eager loading relationships $flights = Flight::with('passengers')->get(); $flights = Flight::with(['passengers', 'crew'])->get(); ``` ### Controllers Controllers organize request handling logic into classes. They are stored in `app/Http/Controllers`. ```php <?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; use Illuminate\View\View; class UserController extends Controller { // Dependency injection via constructor public function __construct( protected UserRepository $users, ) {} // Display a listing of users public function index(): View { $users = User::all(); return view('users.index', ['users' => $users]); } // Store a newly created user public function store(Request $request) { $validated = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users', ]); $user = User::create($validated); return redirect()->route('users.show', $user); } // Display a single user public function show(User $user): View { return view('users.show', ['user' => $user]); } // Single action controller public function __invoke(Request $request) { return User::all(); } } // Generate controller via Artisan // php artisan make:controller UserController // php artisan make:controller PhotoController --resource // php artisan make:controller ProvisionServer --invokable ``` ### Middleware Middleware filters HTTP requests entering your application. ```php <?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class EnsureTokenIsValid { public function handle(Request $request, Closure $next): Response { if ($request->input('token') !== 'my-secret-token') { return redirect('home'); } return $next($request); } } // Middleware that performs action after response class AfterMiddleware { public function handle(Request $request, Closure $next): Response { $response = $next($request); // Perform action after response... return $response; } } // Register middleware in bootstrap/app.php ->withMiddleware(function (Middleware $middleware) { $middleware->append(EnsureTokenIsValid::class); $middleware->alias([ 'token' => EnsureTokenIsValid::class, ]); }) // Apply middleware to routes Route::get('/profile', function () { // ... })->middleware('token'); Route::middleware(['auth', 'throttle:60,1'])->group(function () { Route::get('/dashboard', function () { // ... }); }); ``` ### Authentication Laravel provides a complete authentication system out of the box. ```php <?php use Illuminate\Support\Facades\Auth; use Illuminate\Http\Request; // Attempt authentication if (Auth::attempt(['email' => $email, 'password' => $password])) { $request->session()->regenerate(); return redirect()->intended('dashboard'); } // Authenticate with "remember me" Auth::attempt(['email' => $email, 'password' => $password], $remember); // Check if user is authenticated if (Auth::check()) { // User is logged in... } // Get the authenticated user $user = Auth::user(); $id = Auth::id(); // Logout Auth::logout(); $request->session()->invalidate(); $request->session()->regenerateToken(); // Authenticate a specific user instance Auth::login($user); Auth::login($user, $remember = true); // Authenticate by ID Auth::loginUsingId(1); // Using guards for different authentication types $user = Auth::guard('admin')->user(); Auth::guard('web')->logout(); // Password confirmation Route::get('/settings', function () { // ... })->middleware(['auth', 'password.confirm']); ``` ### Validation Laravel provides multiple approaches to validate incoming data. ```php <?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use App\Http\Requests\StorePostRequest; // Validation in controller public function store(Request $request) { $validated = $request->validate([ 'title' => 'required|unique:posts|max:255', 'body' => 'required', 'email' => 'required|email', 'publish_at' => 'nullable|date', 'author.name' => 'required', 'tags.*' => 'required|string', ]); // Data is valid, create the post... } // Custom error messages $request->validate([ 'title' => 'required', ], [ 'title.required' => 'A title is required', ]); // Using Validator facade $validator = Validator::make($request->all(), [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]); if ($validator->fails()) { return redirect('post/create') ->withErrors($validator) ->withInput(); } // Form Request validation class // php artisan make:request StorePostRequest class StorePostRequest extends FormRequest { public function authorize(): bool { return $this->user()->can('create', Post::class); } public function rules(): array { return [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]; } } // Use in controller public function store(StorePostRequest $request) { $validated = $request->validated(); // ... } ``` ### Queues & Jobs Laravel's queue system allows deferring time-consuming tasks for background processing. ```php <?php namespace App\Jobs; use App\Models\Podcast; use App\Services\AudioProcessor; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use Illuminate\Queue\Attributes\Tries; use Illuminate\Queue\Attributes\Timeout; use Illuminate\Queue\Middleware\WithoutOverlapping; #[Tries(3)] #[Timeout(120)] class ProcessPodcast implements ShouldQueue { use Queueable; public function __construct( public Podcast $podcast, ) {} public function handle(AudioProcessor $processor): void { // Process the podcast... } public function failed(?Throwable $exception): void { // Handle job failure... } public function middleware(): array { return [new WithoutOverlapping($this->podcast->id)]; } } // Dispatching jobs use App\Jobs\ProcessPodcast; ProcessPodcast::dispatch($podcast); ProcessPodcast::dispatch($podcast)->onQueue('processing'); ProcessPodcast::dispatch($podcast)->delay(now()->addMinutes(10)); ProcessPodcast::dispatchIf($condition, $podcast); // Job chaining use Illuminate\Support\Facades\Bus; Bus::chain([ new ProcessPodcast($podcast), new OptimizePodcast($podcast), new ReleasePodcast($podcast), ])->dispatch(); // Job batching $batch = Bus::batch([ new ImportCsv(1, 100), new ImportCsv(101, 200), new ImportCsv(201, 300), ])->then(function (Batch $batch) { // All jobs completed successfully... })->catch(function (Batch $batch, Throwable $e) { // First batch job failure detected... })->finally(function (Batch $batch) { // Batch finished executing... })->dispatch(); // Running the queue worker // php artisan queue:work // php artisan queue:work redis --queue=high,default // php artisan queue:work --tries=3 --timeout=60 ``` ### Blade Templates Blade is Laravel's templating engine providing template inheritance and components. ```php {{-- Displaying data --}} Hello, {{ $name }}. The current UNIX timestamp is {{ time() }}. {{-- Escape HTML entities (default) --}} {{ $userInput }} {{-- Display raw, unescaped data --}} {!! $html !!} {{-- Conditional statements --}} @if (count($records) === 1) I have one record! @elseif (count($records) > 1) I have multiple records! @else I don't have any records! @endif @unless (Auth::check()) You are not signed in. @endunless @auth // User is authenticated... @endauth @guest // User is not authenticated... @endguest {{-- Loops --}} @foreach ($users as $user) <p>This is user {{ $user->id }}</p> @endforeach @forelse ($users as $user) <li>{{ $user->name }}</li> @empty <p>No users</p> @endforelse @for ($i = 0; $i < 10; $i++) The current value is {{ $i }} @endfor {{-- Layout using components --}} {{-- resources/views/components/layout.blade.php --}} <html> <head><title>{{ $title ?? 'Default Title' }}</title></head> <body> <header>{{ $header }}</header> <main>{{ $slot }}</main> </body> </html> {{-- Using the layout --}} <x-layout> <x-slot:title>Custom Title</x-slot> <x-slot:header> <h1>Welcome</h1> </x-slot> <p>Main content here...</p> </x-layout> {{-- Including subviews --}} @include('shared.errors') @include('view.name', ['status' => 'complete']) {{-- Passing data to components --}} <x-alert type="error" :message="$message" /> ``` ### Database Migrations Migrations provide version control for your database schema. ```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(): void { Schema::create('flights', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('airline'); $table->text('description')->nullable(); $table->integer('capacity')->unsigned(); $table->decimal('price', 8, 2); $table->boolean('active')->default(true); $table->json('metadata'); $table->foreignId('user_id')->constrained()->cascadeOnDelete(); $table->timestamps(); $table->softDeletes(); $table->index('name'); $table->unique('airline'); }); } public function down(): void { Schema::dropIfExists('flights'); } }; // Modifying tables Schema::table('users', function (Blueprint $table) { $table->string('phone')->nullable()->after('email'); $table->dropColumn('votes'); $table->renameColumn('from', 'to'); }); // Available column types $table->bigIncrements('id'); // Auto-incrementing UNSIGNED BIGINT $table->bigInteger('votes'); // BIGINT $table->boolean('confirmed'); // BOOLEAN $table->date('created_at'); // DATE $table->dateTime('created_at'); // DATETIME $table->decimal('amount', 8, 2); // DECIMAL with precision $table->enum('level', ['easy', 'hard']); // ENUM $table->float('amount'); // FLOAT $table->json('options'); // JSON $table->string('name', 100); // VARCHAR $table->text('description'); // TEXT $table->timestamp('added_at'); // TIMESTAMP $table->uuid('id'); // UUID $table->vector('embedding', 100); // VECTOR (for AI/ML embeddings) // Artisan commands // php artisan make:migration create_flights_table // php artisan migrate // php artisan migrate:rollback // php artisan migrate:fresh --seed ``` ### Laravel AI SDK Laravel 13 introduces the AI SDK for interacting with AI providers like OpenAI, Anthropic, and Google. ```php <?php // Generate an AI agent // php artisan make:agent SalesCoach namespace App\Agents; use Illuminate\AI\Agent; use Illuminate\AI\Prompt; use Illuminate\AI\Tools\Tool; class SalesCoach extends Agent { protected string $model = 'claude-sonnet-4-20250514'; protected string $provider = 'anthropic'; #[Prompt] public function systemPrompt(): string { return <<<'PROMPT' You are a professional sales coach. Help users improve their sales techniques and provide actionable advice. PROMPT; } // Define a tool the agent can use #[Tool('Get current sales metrics for a user')] public function getSalesMetrics(int $userId): array { return SalesMetric::where('user_id', $userId)->get()->toArray(); } } // Using the agent use App\Agents\SalesCoach; $response = SalesCoach::prompt('How can I improve my closing rate?'); echo $response->text; // Structured output with schema use Illuminate\AI\Value\Schema; class RecommendationSchema extends Schema { public function __construct( public string $title, public string $description, public int $priority, public array $actionItems, ) {} } $response = SalesCoach::prompt('Analyze my performance') ->withSchema(RecommendationSchema::class) ->generate(); $recommendation = $response->structured; echo $recommendation->title; // Using different providers use Illuminate\Support\Facades\AI; // OpenAI $response = AI::using('openai') ->model('gpt-4o') ->prompt('Explain quantum computing') ->generate(); // Anthropic $response = AI::using('anthropic') ->model('claude-sonnet-4-20250514') ->prompt('Write a poem about Laravel') ->generate(); // Streaming responses AI::prompt('Tell me a story') ->stream(function ($chunk) { echo $chunk; }); // Multi-turn conversations $conversation = AI::conversation() ->system('You are a helpful assistant.') ->user('What is Laravel?') ->assistant('Laravel is a PHP web framework...') ->user('How do I install it?') ->generate(); ``` ### Artisan Console Commands Laravel's Artisan CLI provides helpful commands for development. ```php <?php namespace App\Console\Commands; use Illuminate\Console\Command; class SendEmails extends Command { protected $signature = 'mail:send {user : The ID of the user} {--queue : Whether to queue the email}'; protected $description = 'Send a marketing email to a user'; public function handle(): int { $userId = $this->argument('user'); $shouldQueue = $this->option('queue'); $this->info('Sending email...'); $this->line('Processing user: ' . $userId); if ($this->confirm('Do you wish to continue?')) { // Send email... $this->info('Email sent successfully!'); } $this->table( ['Name', 'Email'], User::all(['name', 'email'])->toArray() ); return Command::SUCCESS; } } // Common Artisan commands // php artisan serve - Start development server // php artisan make:model Flight -mfc - Create model with migration, factory, controller // php artisan make:controller API/UserController --api // php artisan migrate:fresh --seed - Fresh migration with seeders // php artisan route:list - List all routes // php artisan config:cache - Cache configuration // php artisan optimize - Optimize for production // php artisan tinker - Interactive REPL ``` --- ## Summary Laravel 13 represents a mature, feature-complete framework that excels in building applications of any scale, from simple APIs to complex enterprise systems. Its primary use cases include building RESTful APIs with automatic JSON resource transformation, full-stack web applications with server-side rendering via Blade templates, real-time applications using Laravel's broadcasting and WebSocket support, background job processing for data pipelines and email queues, and AI-powered applications using the new AI SDK. The framework's modular architecture allows developers to use only the components they need while maintaining a consistent, well-documented API across all features. For integration patterns, Laravel works seamlessly with frontend frameworks through Inertia.js for React/Vue SPAs, or as a pure API backend for mobile applications and separate frontend projects. The framework integrates with major cloud services through first-party packages like Horizon for Redis queue monitoring, Telescope for debugging, Sanctum for API authentication, and Socialite for OAuth authentication. Laravel's ecosystem also includes Laravel Forge and Laravel Cloud for deployment, making it straightforward to take applications from development to production. The combination of elegant syntax, comprehensive documentation, and a vibrant community makes Laravel an excellent choice for PHP developers seeking a productive, maintainable framework for modern web development.