Search code examples
laravelvariableslaravel-5laravel-bladelaravel-7

How to concatenate string to a $variable in blade?


I want to add a variable( in my case it is called $document) from my database to a URL asset directory in the view of my blade file to enable a user to view the image in the web browser. An example is as follows;

// MyController File

// the variable $code is a parameter I'm accepting from the web.php route file for 
// the function show() to help process the assignment value of $data['document'] without issues

public function show($code)
    {
        //  NB: I am passing the document as an array list item of $data as below, so I can mention it as 
        //  a variable in the blade view file 
        //  $data['document']

        $data['document'] = Auth::user()->documents->where("code", $code)->first();

        return view("documents.show", $data);
    }



// Blade View File

<div class="my-class" style="background: url({{ URL::asset('assets/storage/' +$document->file_url) }}) no-repeat center top; background-size: cover;">
</div> 

Solution

  • You are using the wrong operator. In JavaScript, the concatenation operator is +, but in PHP, it is .. To make the code above work, you would just have to update it to how it looks below.

    // Blade View File
    
    <div class="my-class" style="background: url({{URL::asset('assets/storage/' . $document->file_url)}}) no-repeat center top; background-size: cover;">
    </div> 
    

    NB: Test environment used is Laravel 7+