Bookmarks
ReferenceBackendVerified

PHP and Laravel

PHP and Laravel are a language and a web framework for websites and database-backed APIs. This reference covers Composer, routes, Blade, Eloquent, migrations, queues and deployment.

checked 2 Nov · next check 9 Nov · 51 min read

Sections
13
Reading
51 min
Current version
13.39.0; PHP 8.5.12
Written from
php.net/manual/en

Check status of the reference

Verified 2 Nov · next check 9 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What PHP and Laravel are and how they work

PHP is a general-purpose interpreted scripting language, most often used on the web: the code runs on the server and the client receives only the result, such as HTML or JSON. Laravel is a PHP web framework with routing, the Eloquent ORM, Blade templates, queues and the Artisan console already assembled and configured.

Laravel is used in two ways. As a full-stack framework, it accepts requests and renders pages itself with Blade templates. As an API backend, it serves a single-page or mobile application. In both cases the framework takes care of the database, authentication, queues and mail. A one-off script, such as processing a file or running a cron task, does not need a framework: PHP runs it from the command line, without a web server or browser.

Every request follows the same chain. The web server, such as nginx, passes it to PHP over the FastCGI protocol, usually through PHP-FPM (FastCGI Process Manager). The application’s entry point is public/index.php. Service providers register the framework’s components, then the request passes through middleware to the router, which calls a controller. The response returns through the same middleware in reverse order.

PHP keeps no state between requests: global variables and open connections disappear with the response. The application keeps persistent data in the database, the session and the cache.

Service providers load before routing, so the database, queues and validation are already available in the controller.
  1. The web server sends all requests to public/index.php. The file loads the Composer autoloader and gets the application from bootstrap/app.php; the first thing created is the service container.
  2. The HTTP kernel does the initial setup: error handling, logging and environment detection.
  3. Service providers set up the database, queues, validation and routing: register is called on all of them first, then boot. Your own and third-party providers are listed in bootstrap/providers.php.
  4. Middleware are layers around the application: the session, CSRF token verification, maintenance mode. Some run for every request, others only for their own routes.
  5. The router finds the matching route and calls a closure or a controller method.
  6. The response passes back through the route’s middleware, and the send method delivers it to the client.

What PHP provides and what Laravel provides

TaskPHP aloneLaravel
Receive a requestthe web server passes it to a script over FastCGIa single entry point, public/index.php, and routes in routes/
Render a pagePHP code inside the HTML, between <?php and ?>Blade templates in resources/views
Work with a databaseextensions such as PDOEloquent models in app/Models, migrations and seeders in database/
Background workcommand-line scripts run by cronqueued jobs in app/Jobs, the schedule in routes/console.php
Console commandsphp followed by a script nameArtisan: php artisan list make shows only the generators (make:*)

What to know beforehand

  • HTTP: methods, status codes, headers and cookies — see the “HTTP and REST” reference.
  • SQL: selecting data and joining tables — see the “SQL” reference. Eloquent writes queries for you, but you will still need to read them.
  • The Linux command line: running commands and file permissions — see the “Linux” reference.

Section sources

the section is written from these pages

Cheat sheet

Everyday Composer and Artisan commands. Run Artisan from the project root as php artisan; replace the names in the examples (Post, PostController) with your own. Each command is explained in its own section.

Composer

TaskCommand
Install dependencies from composer.lockcomposer install
Add a packagecomposer require laravel/tinker
Add a development-only packagecomposer require --dev laravel/pail
Update packages and composer.lockcomposer update
Update a single packagecomposer update laravel/framework
Rebuild the autoloadercomposer dump-autoload
Check packages for vulnerabilitiescomposer audit

Artisan

TaskCommand
List commandsphp artisan list
Show help for a commandphp artisan help migrate
Overview: environment, configuration, driversphp artisan about
Development server on port 8000php artisan serve
Server, worker, logs and Vite togethercomposer run dev
Console with the application loadedphp artisan tinker
Model with a migrationphp artisan make:model Post -m
Controller with CRUD methodsphp artisan make:controller PostController --resource
All routesphp artisan route:list
Routes whose URI contains apiphp artisan route:list --path=api

Migrations and seeders

TaskCommand
New migrationphp artisan make:migration create_posts_table
Run pending migrationsphp artisan migrate
Show which migrations have runphp artisan migrate:status
Show the SQL without changing anythingphp artisan migrate --pretend
Roll back the last batch: down removes what was createdphp artisan migrate:rollback
Run in production without a promptphp artisan migrate --force
Seed the databasephp artisan db:seed

Queues

TaskCommand
New jobphp artisan make:job GenerateReport
Start a workerphp artisan queue:work
Worker: 3 attempts, 10 s delayphp artisan queue:work --tries=3 --backoff=10
Restart workers after a deploymentphp artisan queue:restart
List failed jobsphp artisan queue:failed
Retry all failed jobsphp artisan queue:retry all
Run the scheduler locallyphp artisan schedule:work

Cache and optimisation

TaskCommand
Cache configuration, events, routes and viewsphp artisan optimize
Cache only the configurationphp artisan config:cache
Clear the configuration cachephp artisan config:clear
Remove everything optimize createdphp artisan optimize:clear
Restart workers and other long-running processesphp artisan reload
Enable and disable maintenance modephp artisan down, php artisan up

Dangerous commands

TaskCommand
Drop all tables and run the migrations againphp artisan migrate:fresh
The same, then seed the databasephp artisan migrate:fresh --seed
Drop all tables without running migrationsphp artisan db:wipe
Roll back all migrationsphp artisan migrate:reset
Roll back everything and migrate againphp artisan migrate:refresh
Delete all failed job recordsphp artisan queue:flush

Section sources

the section is written from these pages

Installation and first run

Laravel needs PHP, Composer and the laravel installer; the official php.new script installs all three with one command. laravel new creates a project, and composer run dev starts it at http://localhost:8000.

Requirements

You need PHP 8.3 or later with the Ctype, cURL, DOM, Fileinfo, Filter, Hash, Mbstring, OpenSSL, PCRE, PDO, Session, Tokenizer and XML extensions; building CSS and JavaScript requires Node.js with npm, or Bun.

Linux, macOS and Windows: php.new

bashLinux
/bin/bash -c "$(curl -fsSL https://php.new/install/linux/8.5)"

The script installs PHP, Composer and the Laravel installer. On macOS, use mac instead of linux in the URL; the PowerShell command for Windows is given on the installation page. Restart the terminal after installing; running the same command again updates all three programs. On macOS and Windows you can install Laravel Herd instead, an application with PHP and nginx built in.

Ubuntu and Debian: distribution packages

PHP is available in the Debian and Ubuntu repositories. These builds are made by the distribution, not by the PHP project, so bugs in them are reported to the package maintainers. Extensions are installed as separate packages with the php- prefix:

bashon a development machine
sudo apt updatesudo apt install php-cli php-curl php-mbstring \  php-xml php-sqlite3# find an extension package, for example for PostgreSQLapt search php | grep -i pgsql

For this kind of setup, install Composer by following the instructions on getcomposer.org. Once PHP and Composer are in place, add the Laravel installer through Composer:

bash
composer global require laravel/installer

Your first project

bash
laravel new example-appcd example-appnpm install && npm run buildcomposer run dev

composer run dev starts the development server, a queue worker and the Vite server; the application opens at http://localhost:8000. By default the project uses SQLite: the database/database.sqlite file and the tables are created during installation. Without the installer, composer create-project laravel/laravel example-app also creates a project.

textproject structure
example-app/├── app/           models, controllers, jobs├── bootstrap/     app.php: framework bootstrap├── config/        configuration files├── database/      migrations, factories, seeders├── public/        index.php and static files├── resources/     views and CSS/JS sources├── routes/        routes: web.php, console.php├── storage/       logs, cache, application files├── tests/         tests├── vendor/        Composer packages├── .env           environment settings└── artisan        Artisan console

The .env file

The .env file in the project root holds whatever differs between machines: the environment, the application key APP_KEY and database access. The installer creates it from .env.example and has already written APP_KEY into it. Do not commit .env to Git: each machine has its own values, and anyone with access to the repository could read the passwords from its history. .env.example, which lists the variables without secrets, should be committed.

ini.env
APP_NAME=BlogAPP_ENV=localAPP_DEBUG=trueAPP_URL=http://localhost:8000 DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=blogDB_USERNAME=blogDB_PASSWORD=change-me

For MySQL or PostgreSQL, create the database, set the DB_* variables and run the migrations. In .env, the values true, false, null and empty become a boolean, null and an empty string; wrap a value containing spaces in double quotes.

bash
php artisan migrate

Verifying the installation

bash
php artisan about --only=environment

The command prints a summary of the application’s environment; without --only it also shows the configuration and drivers. php -v and php artisan --version show the PHP and framework versions; with a php.new installation and no separate web server, php artisan serve serves the page at http://localhost:8000. If it opens the welcome page, the installation is complete.

Section sources

the section is written from these pages

The PHP you need for Laravel

Laravel code relies on a handful of PHP features: namespaces and use, classes with declared types, constructor property promotion and traits. The Composer autoloader loads class files, so require rarely appears in application code.

phpPostController.php
<?php namespace App\Http\Controllers; use App\Models\Post;use App\Services\PostPublisher;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request; class PostController extends Controller{    public function __construct(        private PostPublisher $publisher,    ) {}     public function store(Request $request): RedirectResponse    {        $post = $this->publisher->publish($request->user(), [            'title' => $request->input('title'),        ]);         return redirect()->route('posts.show', $post);    }}
  • namespace sets the class’s namespace, and use imports classes from other namespaces so you can write Post instead of App\Models\Post.
  • A parameter’s type and the return type after : are checked when the method is called: a value of the wrong type throws a TypeError.
  • private PostPublisher $publisher in the constructor parameters declares a property and assigns the argument to it at the same time.
  • ['title' => …] is an array with a key; this is how Laravel code passes data, validation rules and settings.

Variables, strings and arrays

A variable starts with a $ sign, and its type is not declared in advance. A double-quoted string inserts variables directly into the text (interpolation); a single-quoted string does not. PHP has a single array type: a list uses the keys 0, 1, 2…, and an associative array uses named keys written with =>.

php
<?php $user = 'Ali';$count = 2;$summary = "$user has $count drafts"; // interpolation $tags = ['php', 'laravel'];              // list$post = ['title' => 'First post', 'tags' => $tags];$post['views'] = 0;                      // the key is created on assignment foreach ($post['tags'] as $tag) {    $post['views'] += 1;} echo $summary, ' — ', $post['title'];

Namespaces and use

use imports a class, a function (use function) or a constant (use const), and as gives it an alias. An import applies only within its own file and is written at the top level or inside a namespace, but not inside a function. A fully qualified name with a leading \ is not affected by imports.

php
use App\Models\Post;use App\Models\User as Author;use Illuminate\Support\Facades\{DB, Hash}; $post = new Post();// fully qualified name: no import needed$now = new \DateTimeImmutable();

The Composer autoloader finds a class file following the PSR-4 standard: the autoload section of composer.json maps a namespace prefix to a directory. In a Laravel project, App\ is mapped to app/, so App\Models\Post lives in app/Models/Post.php. After editing the autoload section, run composer dump-autoload.

jsoncomposer.json
{    "autoload": {        "psr-4": {            "App\\": "app/"        }    }}

Types and strict_types

Types are declared on parameters, return values and properties. ?string (nullable) means a string or null, the same as string|null; the union int|string accepts either type. By default, PHP coerces a scalar value to the required type: the string '3' passed to an int parameter becomes the number 3.

declare(strict_types=1); at the top of a file enables strict mode: only a value of exactly the right type is accepted, otherwise a TypeError is thrown. There is one exception: an int is accepted where a float is expected, both in arguments and in return values. The mode applies to calls made from that file, and only to scalar types.

php
<?php declare(strict_types=1); function total(int $quantity, float $price): float{    return $quantity * $price;} // 30.0: an int is accepted for a floattotal(3, 10);// TypeError: a string is not coerced to inttotal('3', 10.0);

Constructor property promotion

A constructor parameter with a modifier (public, protected, private or readonly) immediately becomes a property of the object, and the argument is assigned to it automatically. This is constructor property promotion, and the constructor body can be empty. This is how Laravel passes dependencies into controllers and queued jobs.

php
class Money{    public function __construct(        public readonly int $amount,        public readonly string $currency = 'UZS',    ) {}} $price = new Money(150000);echo $price->amount;

Interfaces

An interface defines a set of typed methods that a class must implement; the interface itself contains no behaviour. A class adopts it with the implements keyword and can implement several interfaces at once. Declaring an interface as the type of an argument or property means any class that implements it will do, and the implementation can be swapped without changing the code that depends on it. Laravel injects dependencies by type, and for an interface you first register an implementation in the service container; see the “Routes, controllers and validation” section for details.

php
interface Publisher{    public function publish(object $user, array $data): object;} final class PostPublisher implements Publisher{    public function publish(object $user, array $data): object    {        return (object) ['title' => $data['title']];    }}

Traits

A trait is a set of methods that a class includes with a use line inside the class body; one class can include several traits, but a trait cannot be instantiated. In Laravel, traits add ready-made behaviour: HasFactory gives a model the factory() method, and Queueable adds methods for working with the queue.

phpapp/Models/Post.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model; class Post extends Model{    use HasFactory;}

Arrow functions, enums and attributes

An arrow function is a short form of a closure: fn (type $parameter): type => expression, a single expression with no return, and it captures variables from the outer scope on its own. An enum is a closed set of values; a backed enum (enum Status: string) gives each case a value and the from() and tryFrom() methods. An attribute, #[...], attaches metadata to a class, method or parameter; Laravel reads them through reflection.

php
// arrow function: a short form of a closure$withVat = array_map(    fn (int $price): int => (int) round($price * 1.2),    $prices,); // an enum with values and a methodenum Status: string{    case Draft = 'draft';    case Published = 'published';     public function label(): string    {        return match ($this) {            Status::Draft => 'Draft',            Status::Published => 'Published',        };    }} Status::Published->label();   // “Published”Status::Published->value;     // 'published'Status::tryFrom('nope');      // null, no error // attribute: class metadata#[\Attribute(\Attribute::TARGET_CLASS)]final class Table{    public function __construct(public string $name) {}} #[Table(name: 'posts')]final class Post {} (new ReflectionClass(Post::class))    ->getAttributes(Table::class)[0]->newInstance()->name;// 'posts'

Exceptions

try wraps code that may throw an exception. catch handles it by one type, by several types separated with |, or by their common ancestor Throwable; finally always runs, whether anything was thrown or not. The hierarchy rests on two classes: Exception for application logic errors and Error for errors in PHP itself. Both implement the Throwable interface, so catch (Throwable $e) catches everything.

php
try {    throw new RuntimeException('Service unavailable');} catch (RuntimeException | ValueError $e) {    echo 'rolled back: ', $e->getMessage();} finally {    echo 'connection closed';} try {    intdiv(5, 0);} catch (Throwable $e) {    echo get_class($e); // DivisionByZeroError: an Error is also a Throwable}

The pipe operator

Since PHP 8.5, you can pass a value through a chain of functions with the |> operator: the left side is a value or expression, the right side is a single-argument function, and its result becomes the input of the next one. Wrap arrow functions on the right in parentheses. The chain reads left to right in execution order, with no intermediate variables or nested calls.

php
$slug = '  Post About PHP  '    |> trim(...)    |> (fn (string $s): string => strtolower($s))    |> (fn (string $s): string => str_replace(' ', '-', $s)); echo $slug; // post-about-php// the same without the pipe operator:// str_replace(' ', '-', strtolower(trim('  Post About PHP  ')))

Section sources

the section is written from these pages

Routes, controllers and validation

A route maps an HTTP method and a URL to the code that returns a response: a closure or a controller method. Web routes live in routes/web.php and get session and CSRF protection; API routes live in routes/api.php, with no session and an /api prefix.

phproutes/web.php
<?php use App\Http\Controllers\PostController;use Illuminate\Support\Facades\Route; Route::get('/', function () {    return view('welcome');}); Route::get('/posts/{post}', [PostController::class, 'show'])    ->name('posts.show');

A new project has no routes/api.php: php artisan install:api adds it along with the Sanctum package for API tokens. Besides get, there are post, put, patch, delete and match, which handles several methods at once.

Parameters and model binding

A parameter in curly braces is passed to the handler by position; the argument name does not matter. {name?} is an optional parameter, so the argument needs a default value. If an argument is type-hinted with an Eloquent model and its name matches the parameter, Laravel finds the record itself or responds with 404. This is route model binding. {post:slug} looks the record up by the slug column instead of id.

phproutes/web.php
use App\Models\Post; Route::get('/posts/{post:slug}', function (Post $post) {    return view('posts.show', ['post' => $post]);}); Route::get('/search/{q?}', function (?string $q = null) {    return $q ?? 'empty';});

Names, groups and prefixes

A route name lets you build URLs with the route() function, so links do not break when the path changes. A group sets shared middleware, a URL prefix and a name prefix for many routes at once.

phproutes/web.php
use App\Http\Controllers\Admin\PostController as AdminPosts; Route::middleware(['auth'])    ->prefix('admin')    ->name('admin.')    ->group(function () {        // URL /admin/posts, name admin.posts.index        Route::get('/posts', [AdminPosts::class, 'index'])            ->name('posts.index');    }); $url = route('admin.posts.index');

Middleware

Middleware is a layer a request passes through before reaching the handler, and the response passes through on the way out: login checks, CSRF, logging. Built-in middleware is attached by short name: auth admits only signed-in users, throttle limits the request rate. The php artisan make:middleware command creates your own middleware; assign it to a route with the middleware method, or to every request in bootstrap/app.php.

phpbootstrap/app.php
use App\Http\Middleware\EnsureTokenIsValid; ->withMiddleware(function (Middleware $middleware): void {    // for every request to the application    $middleware->append(EnsureTokenIsValid::class);    // short name for routes: ->middleware('token')    $middleware->alias([        'token' => EnsureTokenIsValid::class,    ]);})
GroupWhat it includesWhere it applies
webcookie encryption, session, validation errors in templates, CSRF verification (PreventRequestForgery), model bindingroutes/web.php
apimodel binding only (SubstituteBindings)routes/api.php

Rate limiting

Define limits in the boot method of AppServiceProvider with RateLimiter::for, then attach the throttle:name middleware to routes. When a limit is exceeded, Laravel responds with 429.

phpAppServiceProvider.php
use Illuminate\Cache\RateLimiting\Limit;use Illuminate\Http\Request;use Illuminate\Support\Facades\RateLimiter; RateLimiter::for('api', function (Request $request) {    // 60 requests per minute per user or IP    return Limit::perMinute(60)        ->by($request->user()?->id ?: $request->ip());});

Controllers

A controller groups request handlers in a class under app/Http/Controllers. A resource controller contains all seven CRUD methods, and Route::resource creates routes for them. Type-hint dependencies in the constructor or in a method: the service container creates and passes them in, which is also how you get the Request object.

bash
php artisan make:controller PostController --resource
phproutes/web.php
Route::resource('posts', PostController::class);
RequestController methodRoute name
GET /postsindexposts.index
GET /posts/createcreateposts.create
POST /postsstoreposts.store
GET /posts/{post}showposts.show
GET /posts/{post}/editeditposts.edit
PUT or PATCH /posts/{post}updateposts.update
DELETE /posts/{post}destroyposts.destroy

For APIs, the --api flag and the Route::apiResource method leave out create and edit, because HTML forms are not needed there.

Request data

phpcontroller method
// form field or JSON, with a default value$title = $request->input('title', 'Untitled');// query string only: /posts?page=2$page = $request->query('page');// true for 1, "1", true, "true", "on" and "yes"$draft = $request->boolean('draft');// uploaded file or null$cover = $request->file('cover');$data = $request->only(['title', 'body']);

Validation

$request->validate() checks the data against the rules and returns the validated fields. On failure, Laravel throws ValidationException: a regular request is redirected back, and the errors and submitted values are flashed to the session. A request that expects JSON gets a 422 Unprocessable Entity response with a list of errors.

phpPostController.php
public function store(Request $request): RedirectResponse{    $validated = $request->validate([        'title' => ['required', 'string', 'max:255'],        'slug' => ['required', 'unique:posts'],        'published_at' => ['nullable', 'date'],    ]);     $post = Post::create($validated);     return redirect()->route('posts.show', $post);}
jsonexample 422 response
{    "message": "The title field is required. (and 1 more error)",    "errors": {        "title": ["The title field is required."],        "slug": ["The slug field is required."]    }}

When there are many rules, move them to a form request class: php artisan make:request StorePostRequest. The rules method returns the rules, and authorize decides whether the action is allowed; on false, Laravel responds with 403. Type-hinting the class as an argument is enough: validation runs before the controller method is called.

phpStorePostRequest.php
class StorePostRequest extends FormRequest{    public function authorize(): bool    {        return $this->user() !== null;    }     public function rules(): array    {        return [            'title' => ['required', 'string', 'max:255'],            'body' => ['required'],        ];    }}
phpPostController.php
public function store(StorePostRequest $request): RedirectResponse{    $post = Post::create($request->validated());     return redirect()->route('posts.show', $post);}

Inspecting routes

bash
php artisan route:list# with each route’s middlewarephp artisan route:list -vphp artisan route:list --path=api

Section sources

the section is written from these pages

Blade templates

Blade is Laravel’s templating engine: .blade.php files in resources/views are compiled to plain PHP and cached. Output written as {{ $value }} is escaped, so user data is not turned into HTML and does not open the door to XSS.

phproutes/web.php
Route::get('/posts', function () {    return view('posts.index', ['posts' => Post::all()]);});

A template name is written with dots: posts.index is the file resources/views/posts/index.blade.php. The second argument of view is an array of data, and its keys become template variables. php artisan make:view creates a new template.

Displaying data

bladeposts/show.blade.php
<h1>{{ $title }}</h1> {{-- escaped: use this for user input --}}<p>{{ $post->body }}</p> {{-- unescaped: only for your own trusted HTML --}}<div>{!! $trustedHtml !!}</div>

{{ }} passes the value through the PHP htmlspecialchars function. {!! !!} prints it as is: do not use this form for user data, or someone else’s <script> ends up on the page.

Conditions and loops

bladeposts/index.blade.php
@if (count($posts) > 10)    <p>Showing the first 10 posts.</p>@endif @foreach ($posts as $post)    <article @class(['first' => $loop->first])>        <a href="{{ route('posts.show', $post) }}">            {{ $post->title }}        </a>    </article>@endforeach @forelse ($comments as $comment)    <p>{{ $comment->body }}</p>@empty    <p>No comments yet.</p>@endforelse

The @if, @foreach, @for and @while directives work like the matching PHP constructs. Inside @foreach, the $loop variable is available: the index of the current iteration, plus $loop->first and $loop->last. @forelse … @empty prints a fallback block when the collection is empty, and @class builds the class attribute from conditions.

Forms: @csrf, @method and errors

bladeposts/edit.blade.php
<form method="POST" action="{{ route('posts.update', $post) }}">    @csrf    @method('PUT')     <input name="title" value="{{ old('title', $post->title) }}">    @error('title')        <p class="error">{{ $message }}</p>    @enderror     <button>Save</button></form>

@csrf adds a hidden _token field: without it, a POST, PUT, PATCH or DELETE request from a form is rejected. HTML forms support only GET and POST, so @method('PUT') adds a _method field and Laravel handles the request as PUT. @error shows a field’s validation message in the $message variable, and old() returns the submitted value after a failed validation.

A layout built from a component

A shared page layout is built as a component: a file in resources/views/components becomes the <x-name> tag. The tag’s content goes into the $slot variable, and named parts go into <x-slot:name>.

bladecomponents/layout.blade.php
<!doctype html><html lang="en"><head>    <title>{{ $title ?? 'Blog' }}</title>    @vite(['resources/css/app.css', 'resources/js/app.js'])</head><body>    {{ $slot }}</body></html>
bladeposts/index.blade.php
<x-layout>    <x-slot:title>All posts</x-slot>     @foreach ($posts as $post)        <h2>{{ $post->title }}</h2>    @endforeach</x-layout>

@vite includes the CSS and JavaScript that Vite builds: with npm run dev they come from the development server, and after npm run build they are the finished, versioned files.

Components with props

bladecomponents/alert.blade.php
@props(['type' => 'info', 'message']) <div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>    {{ $message }}</div>
bladeany template
<x-alert type="error" :message="$error" class="mb-4"/>

@props declares the component’s props and their default values, and the remaining tag attributes are collected in $attributes. A colon before an attribute (:message) passes a PHP expression; without it, a string is passed. php artisan make:component Alert creates a component backed by a PHP class.

Template inheritance

Projects written before components existed build layouts with inheritance: the layout declares @yield('content') placeholders, and a child template starts with @extends('layouts.app') and fills them in with @section directives.

bladeposts/index.blade.php
@extends('layouts.app') @section('title', 'All posts') @section('content')    <p>Post list</p>@endsection

Section sources

the section is written from these pages

Eloquent ORM

Eloquent is Laravel’s ORM: each table has a model class, and each table row is an object of that model. By convention, the Post model works with the posts table, the id primary key and the created_at and updated_at columns, which it fills in itself.

bash
php artisan make:model Post -m

The -m (--migration) flag also creates a migration for the table, and -f, -s and -c add a factory, a seeder and a controller. Models live in app/Models.

phpapp/Models/Post.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Attributes\Fillable;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\BelongsTo;use Illuminate\Database\Eloquent\Relations\HasMany; #[Fillable(['title', 'slug', 'body', 'user_id'])]class Post extends Model{    use HasFactory;     public function user(): BelongsTo    {        return $this->belongsTo(User::class);    }     public function comments(): HasMany    {        return $this->hasMany(Comment::class);    }}

The #[Table('blog_posts')] attribute above the class sets a table with a different name (the Table class is imported from Illuminate\Database\Eloquent\Attributes, like Fillable in the example above). In code written for the Laravel 12 documentation and earlier, the same settings are class properties: protected $table, protected $fillable.

Reading

php
$posts = Post::all();$post = Post::find(1);// 404 response if the record does not exist$post = Post::findOrFail($id); $drafts = Post::where('published', false)    ->orderBy('created_at', 'desc')    ->limit(10)    ->get(); $first = Post::where('slug', 'hello')->first();

all and get return a collection of models; find and first return a single model or null. findOrFail and firstOrFail throw ModelNotFoundException, and if you do not catch it, the client gets a 404. A model is a query builder: all query builder methods are available on it, from where to limit.

Pagination

phpcontroller method
$posts = Post::where('published', true)->paginate(15);
bladetemplate
{{ $posts->links() }}

paginate sets LIMIT and OFFSET from the page parameter in the URL and counts the total number of records. simplePaginate does not count them and needs only one query, which is enough for “Previous” and “Next” links. A paginator returned from a route becomes JSON with the records in data and the fields total, current_page and last_page.

Creating and updating

php
$post = Post::create([    'title' => 'Hello',    'slug' => 'hello',    'body' => 'First post',    'user_id' => $request->user()->id,]); $post->title = 'Hello, world';$post->save(); Post::where('published', false)    ->update(['published' => true]);

save inserts a new record or updates an existing one and sets created_at and updated_at itself. create and update take an array of fields, which is mass assignment.

Mass assignment

By default, every model is protected against mass assignment: create and fill work only if the model has a Fillable attribute (which fields may be filled) or a Guarded attribute (which may not). Without protection, an attacker could add an is_admin field to the form, and create($request->all()) would write it to the database. By default, fields outside Fillable are silently discarded.

phpAppServiceProvider.php
use Illuminate\Database\Eloquent\Model; public function boot(): void{    // locally: throw an exception instead of silently discarding    Model::preventSilentlyDiscardingAttributes(        $this->app->isLocal()    );}

Relationships

A relationship is a model method that returns hasMany, belongsTo or belongsToMany. Eloquent derives the foreign key from the model name: for Post::comments(), it is post_id in the comments table. Read a relationship as a property — $post->comments returns a collection — or call it as a method to add conditions: $post->comments()->where(...).

RelationshipMethod in the modelWhere it is stored
one to many$this->hasMany(Comment::class) in Postpost_id column in comments
its inverse$this->belongsTo(Post::class) in Commentpost_id column in comments
many to many$this->belongsToMany(Tag::class) in Postpost_tag table with post_id and tag_id columns
php
// many to many: rows in the post_tag pivot table$post->tags()->attach($tagId);$post->tags()->detach($tagId);

Eager loading and N+1

A relationship read as a property is lazy-loaded: with a separate query at the moment of access. In a loop over 25 posts, that is 26 queries: one for the posts and one for each post’s author. This is the N+1 problem. with() loads the relationship up front, leaving two queries.

On the left, the number of queries grows with the number of posts; on the right, there are always two.
php
// 2 queries instead of 1 + N$posts = Post::with('user')->get(); foreach ($posts as $post) {    echo $post->user->name;} // several relationships and a nested one$posts = Post::with(['user', 'comments.user'])->get();
phpAppServiceProvider.php
public function boot(): void{    // outside production, lazy loading throws an exception    Model::preventLazyLoading(! $this->app->isProduction());}

With preventLazyLoading, every lazy load throws LazyLoadingViolationException, so a forgotten with() shows up during development.

Query builder

Without a model, DB::table builds the query, and the result is a collection of stdClass objects. The builder passes values through PDO parameter binding, so strings from a user request do not need escaping. PDO cannot bind column names, so never take them from user input, including the sort column.

php
use Illuminate\Support\Facades\DB; $users = DB::table('users')    ->where('votes', '>', 100)    ->get(); // raw expression: pass the value through the ? binding$orders = DB::table('orders')    ->whereRaw('price > ?', [$minPrice])    ->get();

Raw expressions (DB::raw, whereRaw, orderByRaw) go into the SQL as is, and protecting them from SQL injection is up to you: pass values as an array in the second argument. The SQL language is covered in the SQL reference, the section “SELECT: selecting, filtering and sorting”.

Section sources

the section is written from these pages

Migrations and seeders

A migration is a PHP class that changes the database schema: the up method creates tables, columns and indexes, and down reverses it. Migrations live in database/migrations and are kept in Git, so the whole team has the same database schema.

bash
php artisan make:migration create_posts_table

A file name starts with a date and time, which Laravel uses to determine the order. From the name create_posts_table, it understands that the migration creates the posts table and fills in the stub.

phpdatabase/migrations/
<?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('posts', function (Blueprint $table) {            $table->id();            $table->foreignId('user_id')                ->constrained()                ->cascadeOnDelete();            $table->string('title');            $table->string('slug')->unique();            $table->text('body');            $table->boolean('published')->default(false);            $table->timestamps();        });    }     public function down(): void    {        Schema::dropIfExists('posts');    }};
MethodWhat it creates
$table->id()the id primary key: an auto-incrementing UNSIGNED BIGINT (alias of bigIncrements())
$table->string('title')VARCHAR; the length is the second argument
$table->text('body')TEXT
$table->boolean('published')BOOLEAN
$table->decimal('price', 8, 2)DECIMAL: total digits and digits after the decimal point
$table->timestamps()created_at and updated_at
$table->foreignId('user_id')UNSIGNED BIGINT for a foreign key
->nullable()the column can be NULL
->default(false)default value

foreignId('user_id')->constrained() creates the column and a foreign key to users.id: Laravel derives the table from the column name. cascadeOnDelete() deletes the posts along with the user; nullOnDelete() sets NULL instead. Modifiers such as nullable() go before constrained().

->unique() on a column creates a unique index, and $table->index(['user_id', 'created_at']) creates a composite one. To change an existing table, use Schema::table instead of Schema::create.

Running and rolling back

bash
php artisan migratephp artisan migrate:status# show the SQL that would run, without running itphp artisan migrate --pretend

migrate runs only the migrations that have not been applied yet and records them in the migrations table as one batch. migrate:status shows which ones have already run. In production, commands that can lose data ask for confirmation, so add --force in the deployment script.

bash
php artisan migrate:rollback# roll back the last five migrationsphp artisan migrate:rollback --step=5

Why you should not edit applied migrations

Laravel runs a migration once: after migrate, it is recorded in the migrations table and counts as applied. If you edit its file, the change will not run for your colleagues or on the server. To change the schema, create a new migration with Schema::table.

phpa new migration
Schema::table('posts', function (Blueprint $table) {    $table->string('summary')->nullable();});

Seeders

A seeder fills the database with initial or test data, usually using factories. Seeders live in database/seeders; db:seed runs DatabaseSeeder, which calls the others with the call method. Mass assignment protection is disabled while seeding, and in production db:seed asks for confirmation, so add --force in the deployment script.

bash
php artisan make:seeder PostSeederphp artisan db:seedphp artisan db:seed --class=PostSeeder
phpDatabaseSeeder.php
public function run(): void{    $this->call([        UserSeeder::class,        PostSeeder::class,    ]);}

Factories

A factory describes how to produce a model record with random data: the definition method returns the field values, and the fake() helper gives access to the Faker library. A model with the HasFactory trait gets a factory() method: make() creates objects without saving them to the database, and create() saves them.

bash
php artisan make:factory PostFactory
phpPostFactory.php
public function definition(): array{    return [        'user_id' => User::factory(),        'title' => fake()->sentence(),        'slug' => fake()->unique()->slug(),        'body' => fake()->paragraph(),    ];}
phpDatabaseSeeder.php
// 10 users, each with 3 postsUser::factory()    ->count(10)    ->has(Post::factory()->count(3))    ->create();

Section sources

the section is written from these pages

Queues and jobs

A queue moves slow work, such as parsing a file, sending an email or calling an external API, out of the request and into a background process. The controller puts a job on the queue and responds immediately, and a queue:work worker runs the job separately.

A new project stores the queue in a database table (the database driver); Laravel also works with Redis, Amazon SQS and Beanstalkd. QUEUE_CONNECTION in .env sets the default connection, and the sync driver runs a job immediately, without a queue, for development and tests. Redis itself is covered in the “Redis” reference, in the section “What Redis is and how it works”.

A job always takes the same path: dispatch writes it to the queue, a worker picks it up and calls handle. If handle throws an exception, the job goes back on the queue while attempts remain, and then lands in the failed_jobs table, from where you can retry it.

A job gets one attempt by default: set the number of attempts with --tries or the #[Tries] attribute.

Job

bash
php artisan make:job GenerateReport
phpapp/Jobs/GenerateReport.php
<?php namespace App\Jobs; use App\Models\Report;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Queue\Queueable;use Illuminate\Queue\Attributes\Backoff;use Illuminate\Queue\Attributes\Tries; #[Tries(3)]#[Backoff([10, 60])]class GenerateReport implements ShouldQueue{    use Queueable;     public function __construct(        public Report $report,    ) {}     public function handle(): void    {        // collect the data and save the report file    }}

A class that implements ShouldQueue runs on the queue. A model passed to the constructor is queued by its identifier only, and the worker reloads it from the database. #[Tries(3)] allows three attempts, and #[Backoff([10, 60])] waits 10 and 60 seconds before the retries. Without them a job runs once, and a retry after an error happens immediately.

Dispatching a job

phpReportController.php
use App\Jobs\GenerateReport; $report = Report::create($validated); GenerateReport::dispatch($report); // no earlier than 10 minutes from nowGenerateReport::dispatch($report)    ->delay(now()->plus(minutes: 10)); // onto a separate reports queueGenerateReport::dispatch($report)->onQueue('reports');

The arguments of dispatch are passed to the job’s constructor. dispatchSync runs the job immediately in the current process, without a queue.

Worker

bash
php artisan queue:work# queues in priority order, 3 attempts, 10-second pausephp artisan queue:work \  --queue=reports,default \  --tries=3 \  --backoff=10

A worker is a long-running process: it keeps the loaded application in memory and does not see code changes. After every deployment run php artisan queue:restart: the workers finish their current job and exit, and Supervisor starts them again. The restart signal is stored in the cache, so the cache must be configured. In development queue:listen picks up new code by itself, but it is noticeably slower.

bashafter a deployment
php artisan queue:restart

Failed jobs

A job that has used up its attempts is written to the failed_jobs table. A new project already has its migration; if not, php artisan make:queue-failed-table creates it. Jobs run through dispatchSync never end up there.

bash
php artisan queue:failedphp artisan queue:retry ce7bb17c-cdd8-41f0-a8ec-7b4fef4e5ecephp artisan queue:retry all# delete a single entryphp artisan queue:forget ce7bb17c-cdd8-41f0-a8ec-7b4fef4e5ece

queue:failed shows the ID, connection, queue and time of the failure; use the ID to retry or delete a job. queue:prune-failed deletes entries older than 24 hours.

Supervisor

In production queue:work has to run all the time, yet the process can exit, because of the --max-time limit or after queue:restart. Supervisor watches the workers and restarts them. On Ubuntu it is installed from packages, and programs are defined in the /etc/supervisor/conf.d directory.

bashon the server
sudo apt-get install supervisor
inilaravel-worker.conf
[program:laravel-worker]process_name=%(program_name)s_%(process_num)02dcommand=php /srv/blog/artisan queue:work --sleep=3 --tries=3 --max-time=3600autostart=trueautorestart=truestopasgroup=truekillasgroup=trueuser=www-datanumprocs=4redirect_stderr=truestdout_logfile=/srv/blog/storage/logs/worker.logstopwaitsecs=3600

numprocs is the number of workers to start. stopwaitsecs must be longer than your longest job, otherwise Supervisor kills it on stop.

bashon the server
sudo supervisorctl rereadsudo supervisorctl updatesudo supervisorctl start "laravel-worker:*"

Scheduler

Define recurring tasks in routes/console.php with the Schedule facade. On a server a single cron line is enough (it is in the “Deployment” section): schedule:run checks every minute what is due to run. Locally, php artisan schedule:work replaces cron.

phproutes/console.php
use Illuminate\Support\Facades\Schedule; Schedule::command('queue:prune-failed')->daily();

Section sources

the section is written from these pages

Deployment

In production Laravel runs behind a web server: nginx serves files from public/ and passes other requests to PHP-FPM, Supervisor keeps the queue workers running, and cron starts the scheduler. Every deployment installs dependencies without development packages, runs migrations and caches the configuration.

The web server root is the public/ directory, which holds only index.php and static files. If you serve the whole project directory, .env and other configuration files become public. Laravel itself writes to storage/ and bootstrap/cache/: the user the web server process runs as needs write access to both directories.

PHP-FPM, the workers and the scheduler all use the same code, the same .env and the same database.

Server requirements

You need PHP 8.3 or newer with the Ctype, cURL, DOM, Fileinfo, Filter, Hash, Mbstring, OpenSSL, PCRE, PDO, Session, Tokenizer and XML extensions.

nginx configuration

The Laravel documentation gives this starter configuration. Requests that match no file go to public/index.php; other .php files and hidden files, except .well-known, are blocked. The nginx directives are explained in the “Nginx” reference, in the section “Reverse proxy”.

nginxsites-available/blog
server {    listen 80;    listen [::]:80;    server_name example.com;    root /srv/blog/public;     add_header X-Frame-Options "SAMEORIGIN";    add_header X-Content-Type-Options "nosniff";     index index.php;    charset utf-8;     location / {        try_files $uri $uri/ /index.php?$query_string;    }     location = /favicon.ico { access_log off; log_not_found off; }    location = /robots.txt  { access_log off; log_not_found off; }     error_page 404 /index.php;     location ~ ^/index\.php(/|$) {        # the socket path depends on the PHP version        fastcgi_pass unix:/var/run/php/php8.5-fpm.sock;        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;        include fastcgi_params;        fastcgi_buffer_size 32k;        fastcgi_buffers 8 32k;        fastcgi_busy_buffers_size 64k;        fastcgi_hide_header X-Powered-By;    }     location ~ \.php$ {        return 404;    }     location ~ /\.(?!well-known).* {        deny all;    }}

Deployment steps

bashon the server, in the project directory
composer install --no-dev --optimize-autoloaderphp artisan migrate --forcephp artisan optimizephp artisan reload
  1. composer install installs packages exactly as pinned in composer.lock, --no-dev skips require-dev, and --optimize-autoloader turns PSR-4 autoloading into a class map. This is faster, and Composer recommends it for production.
  2. migrate --force runs pending migrations without the confirmation prompt, which would otherwise stop a script in production.
  3. optimize caches the configuration, events, routes and Blade templates.
  4. reload terminates long-running processes (queue workers, Reverb, Octane), and the process monitor starts them again with the new code.

Environment: APP_ENV and APP_DEBUG

ini.env on the server
APP_ENV=productionAPP_DEBUG=falseAPP_URL=https://example.com

APP_ENV sets the current environment, and a server environment variable with the same name takes precedence over the value in .env. With APP_DEBUG=true, users see error details along with the application’s settings, so in production it is always false.

Background processes

Supervisor keeps the queue:work workers running; its configuration is in the “Queues and jobs” section. The scheduler needs only one cron line for the user the application runs as:

textcrontab
* * * * * cd /srv/blog && php artisan schedule:run >> /dev/null 2>&1

Health check

The /up route returns 200 if the application booted without exceptions and 500 on an error. Uptime monitors and load balancers poll it. Change the path with the health parameter in bootstrap/app.php.

bash
curl -I https://example.com/up

Building an image with Laravel is covered in the “Docker” reference, in the section “Dockerfile and its instructions”.

Section sources

the section is written from these pages

Security

Laravel closes the main holes by default: it verifies where requests come from (CSRF), escapes Blade output, binds SQL parameters and hashes passwords. Holes appear when you bypass that protection: {!! !!}, raw SQL containing user input, APP_DEBUG=true in production.

CSRF

Cross-site request forgery (CSRF) is when another site submits a form on behalf of a signed-in user. The PreventRequestForgery middleware in the web group checks every POST, PUT, PATCH, DELETE and QUERY request in two layers. First it looks at the Sec-Fetch-Site header: a same-origin request passes at once. If that check fails, for example because the browser is old or the connection is not HTTPS, the session’s CSRF token is compared instead.

bladeBlade template
<form method="POST" action="/profile">    @csrf    <input name="email" type="email"></form>

The token is sent in the _token field (which @csrf adds) or in the X-CSRF-TOKEN header. Laravel also stores the token in the encrypted XSRF-TOKEN cookie, which Axios and Angular send back automatically in the X-XSRF-TOKEN header. A request that fails the check gets 419, or 403 in originOnly mode.

Webhooks from payment systems and other services will not send a token. Keep such routes outside the web group or exclude their paths:

phpbootstrap/app.php
->withMiddleware(function (Middleware $middleware): void {    $middleware->preventRequestForgery(except: [        'webhooks/payments/*',    ]);})

SQL injection

The query builder and Eloquent pass values through PDO parameter binding, so you do not need to escape them. The risky spots are where SQL is written as a string: DB::raw, whereRaw, selectRaw, orderByRaw. Laravel inserts these into the query as they are.

phpwrong
// user input inside the SQL$posts = DB::table('posts')    ->whereRaw("title LIKE '%{$request->input('q')}%'")    ->get();
phpright
// the value goes through the ? binding$posts = DB::table('posts')    ->whereRaw('title LIKE ?', ['%'.$request->input('q').'%'])    ->get();

PDO cannot bind column names. If the user chooses the sort order, check the value against a list of allowed columns:

php
$allowed = ['title', 'created_at'];$sort = $request->query('sort');$column = in_array($sort, $allowed, true) ? $sort : 'title'; $posts = DB::table('posts')->orderBy($column)->get();

A general catalogue of web application risks is the “OWASP Top 10” reference, in the section “What the OWASP Top 10 is and how to read it”.

XSS and mass assignment

  • Output data in templates with {{ }}: Blade escapes it, whereas {!! !!} does not. Details are in the “Blade templates” section.
  • Do not pass $request->all() to create and update: allow fields with the #[Fillable] attribute or forbid them with #[Guarded], and take the data from validated(). Details are in the “Eloquent ORM” and “Routes, controllers and validation” sections.

Passwords

Store passwords only as hashes. Hash::make uses bcrypt by default, and Hash::check compares the entered password with the hash. A slow hash is exactly the point: dictionary guessing takes longer. The HASH_DRIVER variable changes the driver, for example to argon2id. Laravel starter kits already hash passwords with bcrypt on registration and login.

php
use Illuminate\Support\Facades\Hash; $plain = $request->input('password');$hash = Hash::make($plain); // true if the password matches the hash$ok = Hash::check($plain, $user->password); // after the hashing settings changeif (Hash::needsRehash($user->password)) {    $user->password = Hash::make($plain);}

Authorisation: gates and policies

Authentication answers who the user is, and authorisation answers what they may do. A gate is a closure for an action without a model, such as signing in to the admin area; a policy is a class with rules for a single model. Laravel discovers a policy by itself if it lives in app/Policies and is named after the model: PostPolicy for Post.

bash
php artisan make:policy PostPolicy --model=Post
phpapp/Policies/PostPolicy.php
public function update(User $user, Post $post): bool{    return $user->id === $post->user_id;}
phpchecks in code
// in a controller: 403 if not allowedif ($request->user()->cannot('update', $post)) {    abort(403);} // on a route: the can middlewareRoute::put('/posts/{post}', [PostController::class, 'update'])    ->can('update', 'post');
bladeBlade template
@can('update', $post)    <a href="{{ route('posts.edit', $post) }}">Edit</a>@endcan
phpAppServiceProvider.php
Gate::define('view-admin', function (User $user) {    return $user->is_admin;}); if (! Gate::allows('view-admin')) {    abort(403);}

Sign-in protocols for external services are covered in the “OAuth and OIDC” reference, in the section “Flows: authorization code, PKCE and others”.

APP_KEY and encryption

APP_KEY is the key Laravel uses to encrypt all cookies, including the session cookie, and data passed to Crypt::encryptString. Every encrypted value is signed with a MAC, so tampering is detected on decryption. php artisan key:generate creates the key with a cryptographically secure generator; the installer usually does this for you.

bash
php artisan key:generate

Changing the key signs every user out, and data encrypted with the old key can no longer be decrypted. For a smooth rotation, list the previous keys, comma-separated, in APP_PREVIOUS_KEYS: Laravel tries them if the current key does not fit.

Debugging and rate limiting

  • In production set APP_DEBUG=false: the debug page shows the application’s settings. Details are in the “Deployment” section.
  • Limit the request rate to sign-in and the API with the throttle middleware: when the limit is exceeded Laravel responds with 429. How to define a limit is in the “Routes, controllers and validation” section.

Section sources

the section is written from these pages

Common errors and diagnostics

Start with the log: Laravel writes exceptions to storage/logs/laravel.log. Locally, enable APP_DEBUG=true to see the detailed error page, and php artisan about shows which environment and drivers the application is really running with.

  1. tail -n 50 storage/logs/laravel.log shows the latest log entries; to follow them live, use php artisan pail or tail -f storage/logs/laravel.log.
  2. php artisan about shows the environment, configuration and drivers.
  3. php artisan config:show database shows which database settings are actually loaded.
  4. php artisan config:clear helps if .env changed but the configuration is cached.

500 error with no details

Cause: with APP_DEBUG=false Laravel does not show the user the exception details, which is correct in production. The error message and stack trace stay in the log.

bashcheck
tail -n 50 storage/logs/laravel.log

Fix: find the exception class, file and line in the log. Locally you can temporarily set APP_DEBUG=true and run php artisan config:clear; never do this on a server.

419 response after submitting a form

Cause: the request failed the CSRF check. The form has no _token field, the session has expired or the session cookie did not reach the server. The token is stored in the session and changes with it.

bladefix
<form method="POST" action="/posts">    @csrf    ...</form>
  • Send requests from JavaScript with the X-CSRF-TOKEN or X-XSRF-TOKEN header.
  • Exclude webhook paths with preventRequestForgery(except: [...]) in bootstrap/app.php.

Changes to .env have no effect

Cause: the configuration is cached by config:cache or optimize, and .env is no longer read. For the same reason env() returns null outside the config/ files.

bashfix
php artisan config:clear# on the server, rebuild the cachephp artisan config:cache

PHP cannot find a class

Cause: the namespace and file path do not match the PSR-4 mapping in composer.json, or the autoloader was not rebuilt after changing the autoload section. In a Laravel project the class App\Models\Post must live in app/Models/Post.php.

bashfix
composer dump-autoload

Every page returns 503

Cause: the application is in maintenance mode after php artisan down, for example because the deployment script stopped before php artisan up. A queue worker does not take new jobs in this mode; if that gets in the way, start it with the --force flag.

bashfix
php artisan up

Database connection error

Cause: a connection error shows up as an exception with the SQLSTATE prefix. Check the DB_* variables in .env, that the database exists, and whether an old configuration is cached. config:show database shows the settings the application actually uses.

bashcheck
php artisan config:show database
bashfix
php artisan config:clearphp artisan migrate

Other common problems

SymptomCauseWhat to do
Sessions and cookies are reset, encryption does not workempty or changed APP_KEYfor a new project, run php artisan key:generate; when rotating, put the old key in APP_PREVIOUS_KEYS
A form field is not saved by createthe model has no #[Fillable] attribute with this field, so it was silently droppedadd the field to Fillable
LazyLoadingViolationExceptionpreventLazyLoading is on and a relationship is loaded in a loopload the relationship up front with with()
404 instead of a recordfindOrFail or route model binding did not find the recordcheck the id or key in the URL, for example {post:slug}
Write error in storage/ or bootstrap/cache/the PHP-FPM user has no write permissiongrant permissions to the web server process owner
429 responsethe throttle middleware limit was hitraise the limit in RateLimiter::for (see the “Routes, controllers and validation” section) or wait
The worker runs old codethe worker keeps the application in memoryphp artisan queue:restart after a deployment
Styles and scripts are not loadedVite assets are not builtnpm run build or npm run dev

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Laravel 13 on PHP 8.5. The latest releases are Laravel 13.40.0 (3 November 2026) and PHP 8.5.12 (22 October 2026). A major Laravel version is released once a year and receives bug fixes for 18 months and security fixes for 2 years; a PHP branch receives 2 years of active support and a further 2 years of security fixes.

PHP branches

BranchStatusLatest releaseSupported until
8.5active support8.5.12 — 22 October 2026bug fixes until 31 December 2027, security until 31 December 2029
8.4active support8.4.27 — 22 October 2026bug fixes until 31 December 2026, security until 31 December 2028
8.3security fixes only8.3.36 — 22 October 202631 December 2027
8.2security fixes only8.2.35 — 22 October 202631 December 2026

Laravel branches

BranchPHPStatusLatest release
138.3–8.5released 17 March 2026; bug fixes until Q3 2027, security fixes until 17 March 202813.40.0 — 3 November 2026
128.2–8.5security fixes only, until 24 February 202712.71.0 — 3 November 2026
118.2–8.4end of life since 12 March 2026—

Laravel follows semantic versioning: breaking changes occur only in major releases, while minor and patch releases can come as often as every week. So in composer.json, use a constraint such as ^13.0.

What changed in Laravel 13 and PHP 8.5

  • Installation and first run: Laravel 13 requires PHP 8.3 or later.
  • Routes, controllers and validation: middleware and policy checks are declared with the #[Middleware] and #[Authorize] attributes right on the controller; JSON:API resources build responses according to the JSON:API specification.
  • Eloquent ORM: PHP attributes now appear in Eloquent, events, notifications, validation and tests; the whereVectorSimilarTo vector search works on PostgreSQL with pgvector.
  • Queues and jobs: the #[Tries], #[Backoff], #[Timeout] and #[FailOnTimeout] attributes; Queue::route(...) sets the connection and queue for a job class in one place.
  • Security: the CSRF middleware is now PreventRequestForgery and checks the request origin while keeping the token check.
  • PHP as far as Laravel is concerned: PHP 8.5 adds the |> operator, clone() with new property values, the #[\NoDiscard] attribute, and the array_first() and array_last() functions. The new URI extension parses addresses according to RFC 3986 and the WHATWG URL standard.

Deprecated and removed

  • PHP 8.5: backticks as a shorthand for shell_exec() are deprecated — call the function instead.
  • PHP 8.5: the cast names (boolean), (integer), (double) and (binary) are deprecated — write (bool), (int), (float) and (string).
  • PHP 8.5: using null as an array key and in array_key_exists() is deprecated, as is a semicolon after case instead of a colon.
  • PHP 8.5: driver-specific methods and constants in the PDO class are deprecated, as are the curl_close(), finfo_close(), imagedestroy() and xml_parser_free() functions.
  • Laravel 11 reached end of life on 12 March 2026, and bug fixes for Laravel 12 ended on 13 August 2026.

How to upgrade

Upgrade one major version at a time — from 12.x to 13.x: the changes in the Upgrade Guide are written for that step and rate the likelihood of impact for each item. In composer.json, raise laravel/framework to ^13.0, along with laravel/boost to ^2.0, laravel/tinker to ^3.0 and the test packages phpunit/phpunit to ^12.0 and pestphp/pest to ^4.0; update the Laravel installer to a version compatible with 13.x. The Upgrade Guide estimates the upgrade at 10 minutes; you can automate it with Laravel Boost, using the /upgrade-laravel-v13 command.

bashafter editing `composer.json`
composer update

Security updates

Laravel — from the laravel/framework security advisories on GitHub:

IdentifierWhat is affectedFixed in
GHSA-f9x3-7vq9-cph6, criticalTokenGuard on MySQL and MariaDB: logging in as another user without their API token13.29.0, 12.68.0
GHSA-5wcm-3v2w-8362relationship inclusion on read endpoints: a request could wipe the related table13.27.0, 12.68.0
GHSA-jh5r-qr3c-85q8debug page with APP_DEBUG=true: XSS through a tooltip13.30.0, 12.69.0
GHSA-crmm-hgp2-wgrptemporary signed URLs for the local disk: expiry bypass and file substitution13.12.0, 12.61.1
GHSA-5vg9-5847-vvmq, highemail validation rule: CRLF injection into outgoing mail13.10.0, 12.60.0
GHSA-63hm-g96r-2m2q, lowConcurrency::run() parallel tasks: forging the internal task result message — when the user’s data is written to standard output13.40.0, 12.71.0

PHP — from the PHP ChangeLog for the 8.5 branch. Fixes were also released in the 8.4, 8.3 and 8.2 branches, under different release numbers; they are listed in the same ChangeLog.

IdentifierWhat is affectedFixed in
GHSA-w8hw-w9fx-j79w, GHSA-6wmf-4rv5-p3rpcore: state corruption on bailout8.5.12
CVE-2026-91768, CVE-2026-91769, CVE-2026-91766 and 8 moreFPM: listen.allowed_clients bypass over IPv6; OpenSSL: TLS host name check against the CN; credential leak on redirects in the HTTP stream wrapper8.5.11
CVE-2026-17543, CVE-2026-17544, CVE-2026-7260, CVE-2026-9672pgsql: SQL injection through E'...' strings; BCMath, Phar, libgd8.5.9
CVE-2026-14355openssl_encrypt() with AES-WRAP-PAD: memory corruption8.5.8
CVE-2026-44927, CVE-2026-44928URI extension: bugs in the uriparser library8.5.7
CVE-2026-6735, CVE-2025-14179 and 10 moreFPM: XSS on the status page; PDO_Firebird: SQL injection; SOAP, mbstring, DOM8.5.6
CVE-2025-14178, CVE-2025-14177, CVE-2025-14180 and 1 morearray_merge(): heap overflow; getimagesize(): memory leak; PDO and URI8.5.1

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “PHP and Laravel” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61