Did you know that we can load specific portions of the blade in Laravel? In this tutorial, we will see how we can render a specific fragment of a blade view in Laravel 9. To do it, Laravel provides @fragment blade directives. In this example, we will see the use case and example source code of in @fragment Laravel.

When we use frontend frameworks such as Turbo and htmx, we need to only return a portion of a Blade template within your HTTP response. Blade "fragments" allow us to do just that. To get started, we have to use a portion of Blade template within @fragment and @endfragment directives:

laravel-fragments-example

app/Http/Controller/AnyController.php

<?php

namespace App\Http\Controllers;

use App\Models\User;

class TutorialController extends Controller
{   
    public function index()
    {   
        $users = User::paginate(2);

        return view('welcome', ['users' => $users])->fragment('user-list');

    }
}

 

And now print this fragment from the view like:

resources/views/welcome.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Laravel 9.x Blade Fragments Tutorial | Laravelia</div>
                <div class="card-body">
                @fragment('user-list')
                    <ul>
                        @foreach ($users as $user)
                            <li>{{ $user->name }}</li>
                        @endforeach
                    </ul>
                @endfragment
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

 

Read also: How To Use Inject Blade Directive In Laravel Blade?

 

Conclusion

I have tried to discuss the clear concept of blade fragments laravel 9l. Now we know how to use fragments in laravel. Hope this fragments laravel controller will help you.