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')

@foreach($notifications as $notification)

{{ $notification->message }}

@endforeach

@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:

@fragment('notification-list')

@forelse($notifications as $notification)
type }}">
{{ $notification->message }}

{{ $notification->created_at->diffForHumans() }}

@empty
No notifications
@endforelse

@endfragment


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 Laravel articles like this directly in your inbox.