Dynamic Page Updates with Laravel Blade Fragments

https://picperf.io/https://laravelnews.s3.amazonaws.com/featured-images/12-12-2024-blade-fragment-cropped.png

Dynamic Page Updates with Laravel Blade Fragments

Blade Fragments enable partial page updates by returning specific template sections, ideal for use with htmx or Turbo frameworks.

Using Blade Fragments

Basic fragment definition and usage:

// In your blade template
@fragment('notification-list')
    <div class="notifications">
        @foreach($notifications as $notification)
            <div class="alert">
                
            </div>
        @endforeach
    </div>
@endfragment

// In your controller
return view('dashboard')
    ->fragment('notification-list');

Real-World Implementation

Example of a live notification system:

<?php

namespace App\Http\Controllers;

use App\Models\Notification;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function store(Request $request)
    {
        $notification = Notification::create([
            'user_id' => auth()->id(),
            'message' => $request->message,
            'type' => $request->type
        ]);

        if ($request->hasHeader('HX-Request')) {
            return view('notifications.index', [
                'notifications' => auth()->user()->notifications()->latest()->get()
            ])->fragmentIf(
                $request->hasHeader('HX-Request'),
                'notification-list'
            );
        }

        return back();
    }

    public function clear(Request $request)
    {
        auth()->user()->notifications()->delete();

        return view('notifications.index', [
            'notifications' => collect()
        ])->fragment('notification-list');
    }
}

Template structure:

<!-- notifications/index.blade.php -->
<div class="container">
    @fragment('notification-list')
        <div class="notification-wrapper">
            @forelse($notifications as $notification)
                <div class="alert alert-">
                    
                    <span class="timestamp">
                        
                    </span>
                </div>
            @empty
                <p>No notifications</p>
            @endforelse
        </div>
    @endfragment
</div>

Blade Fragments represent Laravel’s commitment to modern, interactive web development, offering a server-side solution that integrates seamlessly with progressive enhancement techniques while maintaining the simplicity developers expect from Laravel.


The post Dynamic Page Updates with Laravel Blade Fragments appeared first on Laravel News.

Join the Laravel Newsletter to get all the latest
Laravel articles like this directly in your inbox.

Laravel News