I am allowing user to upload an avatar (profile image) in their profile. While uploading avatar is entirely optional, if user does not have avatar, a default image will be used. However, checking whether a user has an avatar uploaded or not is my problem. It only display an avatar only if user has one.
Below is the code in my view file
@foreach($users as $user)
<div class="d-inline p-2">
<div class="col">
<div class="card" style="width: 18rem; background-color: #162238; color:white;">
<br/>
<img id="nature" src="{{asset('avatars/' . ($user->avatar ?? 'default1.jpg'))}}" class="imogi" style="width: 80px; border-radius: 20%" alt=""/>
<div class="card-body" style="background-color: #162238; color:white;">
<h5 class="card-title" style="background-color: #162238; color:white; text-align:center;">{{$user->name}}</h5>
</div>
<ul class="list-group list-group-light list-group-small" style="background-color: #162238; color:white;">
<li class="list-group-item px-4" style="background-color: #162238; color:white; text-align:center;"><i class="fa fa-building-o" style="color:#3490dc;"></i> {{$user->organization}}</li>
<li class="list-group-item px-4" style="background-color: #162238; color:white; text-align:center;"><i class="fa fa-map-marker" style="color:#3490dc;"></i> {{$user->location}}</li>
<li class="list-group-item px-4" style="background-color: #162238; color:white; text-align:center; color:#3490dc;"><small><i class="fa fa-clock-o" style="color:#3490dc;"></i> joined {{ CarbonCarbon::parse($user->created_at)->diffForHumans() }}</li></small>
</ul>
</div>
</div>
</div>
<br/>
@endforeach
2
Answers
If default1.jpg is in avatars folder, add brackets like so:
That is because dot string concatenation operator has precedence over the null coalescing operator and the result in your way is:
and so default1.jpg is referenced from a wrong location
EDIT
If that is not enough:
If all of this still doesn’t fix, you need to check the page source in the browser to see what is set in the image when the avatar for the user is missing
Once you have checked this, if the users with no avatar have a wrong image name and it’s always the same, you can rename your default1.jpg like the one listed in the users record.
An other option, if certain users have a missing avatar file, can be something like:
(I can’t test it now)
A better solution would be to run a batch that updates records that have a non-existent image
You can create a method in your model to check if the attribute has value. If not then assign an default value. This way you don’t have to write an statement to check if the user has an avatar. For example if the column name is avatar in your table.