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
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 8, 2026
PHP convert array to JSON with error handling and round-trip verification
Converts a PHP array to a JSON string, throws a JsonException on failure, and checks the result is valid and decodes back to the original data. Use it when you...
<?php
declare(strict_types=1);
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();