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> 

2 answers

  • answered 2020-06-27 03:50 niilante

    You are using the wrong operator. In Javascript, the concatenation operator is +, but in PHP, it is .. To make your 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> 
    

  • answered 2020-06-27 05:19 A.A Noman

    You have to use like this

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