Dynamic Page Updates with Laravel Blade Fragments
Last updated on by Harris Raftopoulos
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"> {{ $notification->message }} </div> @endforeach </div>@endfragment // In your controllerreturn 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-{{ $notification->type }}"> {{ $notification->message }} <span class="timestamp"> {{ $notification->created_at->diffForHumans() }} </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.