Code snippets
Code snippets
Copy-ready answers to everyday coding questions, each with a short explanation. Laravel, PHP, JavaScript, SQL, Bash and more.
9 snippets tagged #eloquent · Show all
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 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 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 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();