concatenate Php variable with String inside img src concatenate Php variable with String inside img src laravel laravel

concatenate Php variable with String inside img src


You can do this:

<img src="http://example.com/{{ $user_id }}/picture?type=square">

Or:

<img src="{{ 'http://example.com/' . $user_id . '/picture?type=square'}}">

But it's always a good idea to use asset() helper for this:

<img src="{{ asset($userId . '/picture?type=square') }}">


You need to write it like this:

 <img class="img-responsive" src='http://example.com/{{ $user_id }}/picture?type=square';/>

You don't need to concatenate using . in Blade.


It would be cleaner if you move string concat to the back and can call $user->avatar to get the image url. That can be done using Accessors.

When you use the model in Laravel, the variable you can use is rely directly on the columns of the table of the model. Therefore, you can pass the model object to view and use it gracefully.

However, when the result string has to be transform before usable, like you are facing, then we need to add some logic into it. So we do string concat or whatever statement to make what we want. Yet what if the result is rely on one row of the record and it can be computed automatically without making your code dirty, is that better? And then the Accessors comes.

Accessors is a way to define extra attributes to your record. One good is the problem that you are facing.

Take a look at Accessors syntax before reading my example to see the whole picture. https://laravel.com/docs/5.5/eloquent-mutators#accessors-and-mutators

Here is what you need to do.

In the user model file, add the accessor

protected $appends = ['avatar'];public function getAvatarAttribute(){    // Here you generate user avatar url, $this refer to the User object    return 'http://example.com/' . $this->id . '/picture?type=square';}

In your controller, send the $user as a model variable

$user = auth()->user()->toArray();return view('YOUR_VIEW', [    'user' => $user]);

In your view (blade file), use it!

<img class="img-responsive" src="{{ $user['avatar'] }}" />

So when ever you want to use avatar, you can call $user->avatar or $user['avatar'] directly from user model. And if you have the complex logic to generate user avatar url, you can edit the code in the accessor. You view and controller code will look nicer. :)