Skip to content

Code snippets

Code snippets

Copy-ready answers to everyday coding questions, each with a short explanation. Laravel, PHP, JavaScript, SQL, Bash and more.

29 snippets · Show all

PHP November 2, 2026 Laravel Pest feature test for an API endpoint with a factory Tests that an endpoint creates a record and returns the right JSON. Pest is the default test runner in new Laravel apps. <?php it('creates a post', function () { $user = User::factory()->create(); PHP November 2, 2026 Laravel chunkById and lazy: process large tables without running out of memory Loads rows in batches instead of all at once, so big tables don’t exhaust memory. Prefer chunkById when you update rows while looping. <?php User::chunkById(1000, function ($users) { foreach ($users as $user) { PHP November 2, 2026 Laravel attribute casting and accessors/mutators casts() converts columns to arrays, dates or enums automatically. Attribute::make transforms a value when you read or write it. <?php use Illuminate\Database\Eloquent\Casts\Attribute; PHP November 2, 2026 Laravel database transactions with DB::transaction Runs several writes as one unit: if anything throws, all of them roll back. attempts retries on deadlocks. <?php use Illuminate\Support\Facades\DB; PHP November 2, 2026 Laravel model observers and events with #[ObservedBy] Moves model lifecycle logic (created, updated, deleted) out of controllers into one class. The #[ObservedBy] attribute registers it without a service provider. <?php // php artisan make:observer PostObserver --model=Post use Illuminate\Database\Eloquent\Attributes\ObservedBy; PHP November 2, 2026 Laravel task scheduling in routes/console.php (Laravel 11+) From Laravel 11, schedules live in routes/console.php, not Kernel.php. You need only one cron entry that runs schedule:run every minute. <?php use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schedule; PHP November 2, 2026 Laravel file upload: validate, store and get the URL Validates an uploaded image, stores it on the public disk and builds its URL. Run php artisan storage:link once so the public disk is web-accessible. <?php use Illuminate\Support\Facades\Storage; PHP November 2, 2026 Laravel Sanctum API token authentication Issues API tokens for mobile apps and SPAs. In Laravel 11/12, run php artisan install:api first to set up the API scaffolding. <?php // User model: add the HasApiTokens trait use Laravel\Sanctum\HasApiTokens; PHP November 2, 2026 Laravel Policies and Gates: authorize actions in controllers Keeps permission rules in one policy class instead of scattering if checks. Gate::authorize throws a 403 when the check fails. <?php // php artisan make:policy PostPolicy --model=Post public function update(User $user, Post $post): bool PHP November 2, 2026 Laravel soft deletes: delete, restore and query trashed records Marks a row as deleted instead of removing it, so you can restore it later. withTrashed() and onlyTrashed() let you query deleted rows. <?php // migration $table->softDeletes(); PHP October 19, 2026 Laravel queue job to run slow tasks in the background Moves slow work such as sending email or processing files out of the web request so pages respond fast. Run a worker with php artisan queue:work. <?php // php artisan make:job SendWelcomeEmail namespace App\Jobs; PHP October 19, 2026 Laravel HTTP client retry and timeout for external API calls Calls an external API with a timeout and automatic retries. throw() raises an exception on 4xx and 5xx responses so failures aren’t silent. <?php use Illuminate\Support\Facades\Http; PHP October 19, 2026 Laravel rate limit API routes with throttle middleware Limits how many requests a client can make per minute and returns a 429 when exceeded. Use it on login, API and public endpoints to stop abuse. <?php // routes/api.php: 60 requests per minute Route::middleware('throttle:60,1')->group(function () { PHP October 19, 2026 Laravel API Resource transform model to JSON response Controls exactly which fields your API returns, so you never leak columns by accident. whenLoaded includes a relation only if it was eager loaded, which avoids... <?php // php artisan make:resource PostResource namespace App\Http\Resources; PHP October 19, 2026 Laravel Eloquent local query scope reusable filters Wraps a common where condition in a reusable method on the model. Use it so filters like “published” aren’t repeated across controllers. <?php // app/Models/Post.php use Illuminate\Database\Eloquent\Builder; PHP October 15, 2026 PHP 8 first-class callable, named arguments, str_contains and match(true) strtolower(...) turns any function into a Closure. Named arguments let you reorder or skip parameters, str_contains and its siblings replace strpos checks, and... <?php $lower = strtolower(...); echo $lower('HELLO'), PHP_EOL; // hello PHP October 15, 2026 PHP arrow functions with array_map and array_filter Arrow functions (fn) are one-line closures that capture outer variables by value automatically. Note that array_filter keeps keys, so wrap it in array_values()... <?php $nums = range(1, 10); $result = array_map(fn ($n) => $n ** 2, array_filter($nums, fn ($n) => $n % 2 === 0)); PHP October 15, 2026 PHP null-safe operator ?-> with null coalescing for safe property chains ?-> stops the whole chain and returns null when any link is null, so you don’t need nested if checks. Add ?? for a default value. Needs PHP 8.0+. <?php class Address { public function __construct(public ?string $city = null) {} } class User { public function __construct(public ?Address $address = null) {} } PHP October 15, 2026 PHP readonly class with constructor promotion and named arguments A readonly class makes every property immutable, and constructor promotion removes the boilerplate. “Withers” return a new instance instead of changing the old... <?php final readonly class Point { PHP October 15, 2026 PHP 8.1 enum with methods and match expression Backed enums can hold methods and static helpers. match gives a strict value mapping, and tryFrom with ?? provides a safe fallback. Needs PHP 8.1+. <?php enum Status: string { PHP October 11, 2026 Laravel Request exists() vs has() vs filled() difference exists() is an alias of has(), and both only check that the key was sent, even when its value is empty or null. Use filled() when you need a non-empty value and... <?php use Illuminate\Http\Request; PHP October 10, 2026 Laravel Cache::flexible stale-while-revalidate caching Serves the cached value instantly, even after it goes stale, and refreshes it in the background after the response is sent. Use it for slow queries on busy page... <?php use Illuminate\Support\Facades\Cache; PHP October 10, 2026 Laravel Concurrency::run execute tasks in parallel Runs several closures at the same time and returns their results in order. Use it when a page needs independent slow calls, such as two reports or two APIs, and... <?php use Illuminate\Support\Facades\Concurrency; PHP October 10, 2026 Laravel Context facade add data to every log entry Stores values once and attaches them to all later log entries in the request, and to queued jobs dispatched from it. Use it for a request or trace ID so you can... <?php use Illuminate\Support\Facades\Context; use Illuminate\Support\Facades\Log;

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.