• Laravel
  • 🚀 Useful relatively new Laravel features

    Views32

    #📖 The Developer's Guide to Lesser-Known Utilities


    #⚡ 1. Cache::touch(): Extend TTL Without the Trip

    Introduced in Laravel 13, this is a massive performance win for session-heavy applications. Previously, if you wanted to extend the expiration of a cached item, you had to retrieve the value and re-store it.

    • The Problem: Two network round trips and a full payload transfer.
    • The Solution: Cache::touch('key', $seconds) updates the expiration timestamp directly in the cache store (like Redis) without pulling the data back to your application.
    • Use Case: Extending "sliding" user sessions or keeping "hot" API data alive without wasting bandwidth.

    #🔍 2. Real-Time Validation with Laravel Precognition

    Precognition allows you to use your existing Laravel validation rules to provide live feedback on the frontend before a user even hits "Submit."

    1. It works by sending a "pre-flight" request to your controller.
    2. Laravel runs the validation but skips the actual execution logic (like database writes).
    3. It returns the errors immediately, which your frontend (Vue, React, or Alpine) can display instantly.

    #⏱️ 3. The defer() Helper

    Introduced to help developers avoid the overhead of setting up a full-blown queue for minor tasks, defer() executes logic after the HTTP response has been sent to the user.

     1return tap($user->save(), function () {
     2    defer(fn () => logger("User {$user->id} updated their profile."));
     3});
    

    This ensures the user doesn't experience a delay while the application performs non-critical logging or cleanup.

    #🏷️ 4. Native PHP Attributes for Models

    Laravel 13 has moved heavily toward PHP Attributes. You can now clean up your class bodies by moving metadata into attributes, making the "intent" of the class visible at a glance.

     1<?php
     2#[ScopedConnection('tenant_db')]
     3#[Table('legacy_orders')]
     4class Order extends Model 
     5{ 
     6    // Class body remains clean and focused on logic
     7}
    

    #📊 Feature Summary & Use Cases

    Feature Primary Use Case Core Benefit
    Cache::touch() Session Management Saves bandwidth and reduces latency
    Precognition Complex Web Forms Instant UX feedback without custom JS logic
    defer() Post-request logging/cleanup Faster perceived response times for users
    PHP Attributes Model Configuration Reduces boilerplate and visual noise
    profile image of Petar Vasilev

    Petar Vasilev

    Petar is a web developer at Mitkov Systems GmbH. He is fascinated with the web. Works with Laravel and its ecosystem. Loves learning new stuff.

    More posts from Petar Vasilev