Search code examples
laravellaravel-bladelaravel-7

Laravel - how to create (anonymous) Dynamic Blade Components in Views


Using Laravel 7 with the newly added blade components--

I have some dynamic fields that are returning an array. Inside the array contains each "component" stored as "layout", I have a component that is named exactly after the component class. In my base view, I'm looping through the array and rendering the component:

@if ($page->content)
    //@dd($page->content):
    {{-- array:1 [▼
        0 => {#425 ▼
            +"layout": "wysiwyg"
            +"key": "W0yC0KtNgPV8N4ua"
            +"attributes": {#1303 ▼
            +"alignment": "default"
            +"background_color": "default"
            +"text": "<h1>Hello World</h1>"
            }
        }
        ] --}}
    @foreach ($page->content as $content)
        <x-{{ $content->layout }} :content="$content"/>
    @endforeach
@endif

However, this renders nothing (it's blank). The source of the compiled blade shows <x-wysiwyg :component="$content"/> so it's acting like it's not compiling at all. However, If I update my foreach loop component content explicitly: <x-wysiwyg :content="$content"/>, it works and renders the component.

How can I dynamically load components with values?


Solution

  • This actually isn't possible in Laravel 7 but coming soon to Laravel 8:

    https://twitter.com/taylorotwell/status/1265681297286082562

    <x-dynamic-component :component="$componentName" class="mt-4" />
    

    Edit: Now released - https://laravel.com/docs/8.x/blade#dynamic-components