Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Rendering specific fragment of a blade view in Laravel 9.x

November 10, 2022 ·

Blade views are the most common way to render HTML in Laravel. But, what if you want to render a specific fragment of a blade view? For instance, you want to render a specific section of a blade view. Or, you want to render a specific component of a blade view.

A recent PR was merged in the Laravel framework which allows you to render a specific fragment of a blade view from controllers. So, let’s see how we can do that.

The fragment directive

The @fragment directive was introduced in Laravel 9.x and it allows you to render a specific fragment of a blade view.

Here’s how you can use it. First, you need to create a blade view with a fragment. For instance, let’s create a welcome.blade.php view with the new @fragment directive like so.

<!-- welcome.blade.php -->

<div>
    Welcome to ACME.com!

    @fragment('dialog')
        <div>
            <h1>Rendering from a fragment!</h1>
        </div>
    @endfragment
</div>

And then, you can render the fragment from the controller method like so.

// UserController.php

public function index()
{
    return view('welcome')->fragment('dialog');
}

As you can tell, here, we’re rendering the welcome view and passing the dialog fragment to the fragment method. This will render the dialog fragment of the welcome view. This will render the following HTML.

<div>
    <div>
        <h1>Hi, John!</h1>
    </div>
</div>

Use case

This comes in handy when you want to render a specific fragment of a blade view from a controller. For instance, in cases where you’re working with frontend frameworks that use the HTML over-the-wire concept such as Turbo, Unpoly, Htmx or Pjax and you have to return just a fragment of a view to replace a portion of the DOM.

As per the PR owner, “Fragments are just a way to extract a portion of a view”. So, they should be avoided in using them as a component alternative.


Prefer video format instead? Fret not!

Learn the fundamentals of PHP 8 (includes 8.1 and 8.2), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?