Search code examples
phplaravellaravel-bladelaravel-9

How to return to the DOM a string variable from controller that contains an html image tag with asset() function in src?


I am facing an issue with Laravel 9. In my controller, I have created a variable which contains inside quotes the html code to be returned to the view.

I have a problem to determine where I should use single quotes and double quotes or backticks so that the {{asset()}} in the image src is compiled properly.

for now my image url looks like this in the console : http://127.0.0.1:8000/%7B%7B%20asset(storage/upload/test2-png.png)%20%7D%7D

Here is the error in the console:

GET http://127.0.0.1:8000/%7B%7B%20asset(storage/upload/test2-png.png)%20%7D%7D 404 (Not Found)

Here is the variable I am talking about:

$celebrityDetailsContent = `
                @if(isset($celebrityClicked))
                    <div id="celebrity_text_and_picture_container" class="w-100 p-3">
                        <img src="{{ asset('storage/upload/'.{$celebrityClicked->image}) }}" class="float-start img-border-radius img-thumbnail w-50 m-3" alt="Celebrity photo" title="Celebrity photo">
                        <p class="fw-bold">{$celebrityClicked->firstname} {$celebrityClicked->lastname}</p>
                        <p class="text-start">{$celebrityClicked->description}</p>
                    </div>
                @else 
                    <h2 class="fw-bold">Click on a celebrity to display details</p>
                @endif
            `;

            return $celebrityDetailsContent;

Thanks for your help.


Solution

  • Don't use {{ }} in your controller. It only works in your blade files. Try this:

    if (isset($celebrityClicked)) {
        $celebrityDetailsContent = '
                    <div id="celebrity_text_and_picture_container" class="w-100 p-3">
                        <img src="' . asset('storage/upload/' . $celebrityClicked->image) . '" class="float-start img-border-radius img-thumbnail w-50 m-3" alt="Celebrity photo" title="Celebrity photo">
                        <p class="fw-bold">' . $celebrityClicked->firstname . ' ' . $celebrityClicked->lastname . '</p>
                        <p class="text-start">' . $celebrityClicked->description . '</p>
                    </div>';
    } else {
        $celebrityDetailsContent = '<h2 class="fw-bold">Click on a celebrity to display details</p>';
    }
    
    return $celebrityDetailsContent;