Search code examples
phplaravelassetslaravel-blade

Laravel background-image:url is returning 1


I'm making a webapplication in Laravel. I have the following code snippet:

<div class="user-info" style="background-image:url({{ asset(Auth::user()->partner->background) or '/images/default/background1.jpg'}})">

This is the result in the HTML:

<div class="user-info" style="background-image:url(1)">

What I'm supposed to get is the following from the database:

images/backgrounds/HRVl7TXkAxlhASj14vAV.png

This is weird because if I do the following:

{{dd(Auth::user()->partner->background)}}

it does actually dd() the filename images/backgrounds/HRVl7TXkAxlhASj14vAV.png from the database. Why does it echo 1 istead of the filename when I put it in a background-image:url?


Solution

  • Try

    {!! "'".asset(Auth::user()->partner->background)."'" or '/images/default/background1.jpg'!!}
    

    EDIT

    A bit messy, but should work

    {!! Auth::user()->partner && Auth::user()->partner->background ? "'".asset(Auth::user()->partner->background)."'" : '/images/default/background1.jpg' !!}
    

    I recommend you to write separate method in User for this feature.
    Something like this:

    public function background()
    {
        // your awesome logic
        return $pathToBackground;
    }
    

    and then:

    <div class="user-info" style="background-image:url('{!! asset(Auth::user()->background()) !!}');" >