Code snippets
Code snippets
Copy-ready answers to everyday coding questions, each with a short explanation. Laravel, PHP, JavaScript, SQL, Bash and more.
23 snippets tagged #laravel · 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 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;
PHP
October 10, 2026
Laravel Number helper format numbers as 1.2K, 3M, file sizes
Built-in formatting for abbreviations, currency, file sizes and percentages, so you don’t need to write helpers. Use it in views and API responses. Needs Larave...
<?php
use Illuminate\Support\Number;
PHP
October 8, 2026
Laravel Form Request validation with custom messages
Moves validation out of the controller into a reusable class. Use it for any create or update endpoint; $request->validated() returns only the checked fields, w...
<?php
namespace App\Http\Requests;
PHP
October 8, 2026
Laravel cache expensive query with Cache::remember
Runs the query once and serves the result from cache for the given time. Use it for heavy queries on pages with lots of traffic, and forget the key when the dat...
<?php
use Illuminate\Support\Facades\Cache;
PHP
October 3, 2026
Laravel Eager Loading with Eloquent: Avoid N+1 Queries
Laravel Eloquent eager loading lets you load model relationships in advance using the with() method, helping prevent the N+1 query problem and reducing unnecess...
use App\Models\Post;
// Eager load the author and comments relationships
$posts = Post::with(['author', 'comments'])->get();