Search code examples
laravellaravel-bladelaravel-9laravel-view-component

How to enforcing Laravel to render view components on a string?


I have this string:

<div class="my-card-container">
  <x-card :title="Hello Wordl"></x-card>
</div>

This string is coming from database, it lives in the Conent model's html property. I use it in my ContentController like this:

    public function serve(Request $request, string $uri = ''): View
    {
        $content = Content::whereUri($uri);

        return view('main', [
            'content' => $content->html,
        ]);
    }

In my main.blade.php:

@section('content')
<main>
    @include('main.content')
</main>
@stop

I want to render any available view components on my string.

Can I somehow enforce Laravel to apply the CardComponent or any other available component on that string?


Solution

  • The Blade::render() will help you.

    Try this:

        public function serve(Request $request, string $uri = ''): View
        {
            $content = Content::whereUri($uri);
    
            $content = Blade::render($content);
    
            return view('main', [
                'content' => $content->html,
            ]);
        }