Code snippets
Code snippets
Copy-ready answers to everyday coding questions, each with a short explanation. Laravel, PHP, JavaScript, SQL, Bash and more.
49 snippets
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();
SQL
October 20, 2026
MySQL backup and restore a database with mysqldump
Dumps a database to a file and restores it later. --single-transaction gives a consistent backup of InnoDB tables without locking them.
# Backup
mysqldump -u root -p --single-transaction mydb > mydb.sql
# Backup compressed
SQL
October 20, 2026
MySQL group by month and count rows per period
Counts rows per month for reports and charts. DATE_FORMAT builds the month label to group on.
SELECT DATE_FORMAT(created_at, '%Y-%m') AS month,
COUNT(*) AS orders,
SUM(total) AS revenue
FROM orders
SQL
October 20, 2026
MySQL add an index and check it with EXPLAIN
Adds an index to speed up a slow WHERE clause, then uses EXPLAIN to confirm the query uses it. Check that key is set and rows is small.
ALTER TABLE orders ADD INDEX idx_user_created (user_id, created_at);
EXPLAIN
SELECT * FROM orders
SQL
October 20, 2026
MySQL INSERT ON DUPLICATE KEY UPDATE upsert
Inserts a row, or updates it if a unique key already exists. The table needs a UNIQUE or PRIMARY KEY on the column you match.
INSERT INTO page_views (page, views)
VALUES ('/home', 1)
ON DUPLICATE KEY UPDATE views = views + 1;
SQL
October 20, 2026
MySQL get the Nth highest salary using LIMIT OFFSET
A classic interview question. DISTINCT skips ties, and OFFSET N-1 jumps to the Nth value. This example returns the 2nd highest.
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1; -- change the offset for the 3rd, 4th, etc.
SQL
October 20, 2026
MySQL find and delete duplicate rows keeping the lowest id
Finds rows that repeat a column value and deletes all but the one with the smallest id. Run the SELECT first to preview what will be removed, and back up the ta...
-- Preview duplicates
SELECT email, COUNT(*) AS total
FROM users
GROUP BY email
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;
Bash
October 17, 2026
Linux check disk usage and find the biggest folders
df shows free space per filesystem and du shows what is using it. Use them when a server runs out of disk.
df -h # free space per mount
du -sh * # size of each item here
du -h --max-depth=1 /var | sort -hr | head -10 # top 10 folders in /var
Bash
October 17, 2026
Linux find and kill a process by port or name
Finds what is listening on a port and stops it. Try a normal kill first and only use kill -9 if the process won’t stop.
ss -tulpn | grep :8000 # who is using port 8000
lsof -i :8000 # same, with lsof
kill <PID> # graceful stop
kill -9 <PID> # force stop
Bash
October 17, 2026
Linux tail and follow log files in real time
Watches a log as new lines arrive. Use it to debug a running app or service.
tail -f storage/logs/laravel.log # follow a file
tail -n 100 -f /var/log/nginx/error.log # last 100 lines, then follow
journalctl -u nginx -f # follow a systemd service
journalctl -u nginx --since "1 hour ago"