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.

49 snippets

Bash October 17, 2026 Linux compress and extract tar.gz and zip archives Creates and unpacks the two most common archive formats. tar -czf backup.tar.gz folder/ # create tar.gz tar -xzf backup.tar.gz # extract tar -xzf backup.tar.gz -C /target/ # extract to a folder zip -r site.zip folder/ # create zip Bash October 17, 2026 Linux find files by name, size or age and delete them safely find searches by name, size and modified time. Run it without -delete first to preview what matches. find . -name "*.log" # by name find /var/log -type f -size +100M # larger than 100 MB find . -type f -mtime +30 # older than 30 days find . -name "*.tmp" -type f -print # preview first 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 { JavaScript October 14, 2026 JavaScript dark mode toggle that remembers the user’s choice Uses the system preference on the first visit, then saves the user’s choice in localStorage. It sets a data-theme attribute you can style in CSS. const root = document.documentElement; const saved = localStorage.getItem('theme'); const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; JavaScript October 14, 2026 JavaScript remove duplicates from an array A Set keeps only unique values, so spreading it back into an array removes duplicates. For objects, dedupe by a key with a Map. const nums = [1, 2, 2, 3, 3, 3]; const unique = [...new Set(nums)]; console.log(unique); // [1, 2, 3] JavaScript October 14, 2026 JavaScript fetch with timeout using AbortSignal.timeout Cancels a request automatically if the server takes too long. It also checks response.ok, because fetch does not throw on HTTP errors like 404 or 500. async function getJson(url, ms = 5000) { const res = await fetch(url, { signal: AbortSignal.timeout(ms) }); if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json(); JavaScript October 14, 2026 JavaScript copy text to clipboard with the Clipboard API Copies text with the modern async Clipboard API. It only works on HTTPS (or localhost) and usually needs to run from a user action such as a click. async function copyText(text) { try { await navigator.clipboard.writeText(text); return true; JavaScript October 14, 2026 JavaScript debounce function to limit how often a function runs Delays a function until the user stops triggering it for a set time. Use it for search boxes, window resize and autosave so you don’t fire on every keystroke. function debounce(fn, delay = 300) { let timer; return (...args) => { clearTimeout(timer); 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; JavaScript October 8, 2026 Union, intersection and difference of Sets with built-in Set methods ES2025 adds set-algebra methods to Set, so you no longer write spread-and-filter helpers. They return new Sets. Needs Node 22+, Chrome 122, Firefox 127 or Safar... const a = new Set([1, 2, 3]), b = new Set([3, 4]); console.log(a.union(b), a.intersection(b), a.difference(b), a.symmetricDifference(b)); console.log(new Set([3]).isSubsetOf(a)); // Set(4) { 1, 2, 3, 4 } Set(1) { 3 } Set(2) { 1, 2 } Set(3) { 1, 2, 4 } JavaScript October 8, 2026 Group array items by property with Object.groupBy and Map.groupBy Buckets an array by a callback’s return value, replacing the usual reduce boilerplate. Map.groupBy keeps non-string keys. The Object.groupBy result has a null p... const people = [ { name: "Ann", role: "dev" }, { name: "Bob", role: "ops" }, { name: "Cy", role: "dev" }, JavaScript October 8, 2026 Sort, reverse and update arrays without mutating: toSorted, toReversed, with These methods return a new array and leave the original untouched, which suits React state and other immutable code. Needs Node 20+, Chrome 110, Firefox 115 or... const nums = [3, 1, 2]; const sorted = nums.toSorted((a, b) => a - b); const reversed = nums.toReversed(); const replaced = nums.with(0, 99); JavaScript October 8, 2026 Deep clone objects in JavaScript with structuredClone() Makes a true deep copy and keeps Date, Set and Map. It avoids the JSON.parse(JSON.stringify()) hack, which turns Dates into strings and drops Sets. Needs Node 1... const orig = { user: { name: "Ada", tags: ["a"] }, when: new Date(0), ids: new Set([1, 2]) }; const copy = structuredClone(orig); copy.user.tags.push("b"); console.log(orig.user.tags, copy.user.tags); 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);

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.