Reputation: 81
So i'm creating user profiles in laravel and want to show a generic profile image if the user hasn't uploaded his/her own profile image with the following if/else condition:
@if(false)
<img src="img/uploads/avatars/{{$user->Uname}}" class="img-thumbnail" alt="{{$user->Uname}}'s Profile Pic">
@else
<img src="img/uploads/avatars/{{$user->avatar}}" class="img-thumbnail" alt="{{$user->Uname}}'s Profile Pic">
@endif
I need to check if a file exists with the same name as the user-name of a user (uploads create a file with that name in the above specified location).The false is where the condition for file existence should be but i'm facing 2 problems that i haven't found in other solutions:
The file exists in a path outside of storage. (it exists in public folder)
I want to do it without the use of storage or file facades.
Note: Following changes have been made to filesystems.php
'local' => [
'driver' => 'local',
'root' => storage_path('../public/img/uploads/'),
]
Edit: The problem is similar to the one mentioned here but this solution didn't work for me:Determining If a File Exists in Laravel 5
Edit#2: Final Working Code:
@if(is_file("img/uploads/avatars/{$user->Uname}"))
<img src="img/uploads/avatars/{{$user->Uname}}" class="img-thumbnail" alt="{{$user->Uname}}'s Profile Pic">
@else
<img src="img/uploads/avatars/default.jpg" class="img-thumbnail" alt="{{$user->Uname}}'s Profile Pic">
@endif
Upvotes: 3
Views: 13805
Reputation: 7111
You should check if file exists
@if(is_file('/path/to/file.ext'))
// code
@else
// code
@endif
You could use laravel helpers, something like:
@if(is_file(public_path('img/uploads/avatars/' . $user->Uname)))
//<img src="{{ asset('img/uploads/avatars' . $user->Uname) }}">
Upvotes: 11
Reputation: 680
You don't have your file extension in your image src.
@if(file_exists('img/uploads/avatars/'.$user->Uname.'png'))
<img src="img/uploads/avatars/{{$user->Uname}}.png" class="img-thumbnail" alt="{{$user->Uname}}'s Profile Pic">
@else
<img src="img/uploads/avatars/{{$user->avatar}}.png" class="img-thumbnail" alt="{{$user->Uname}}'s Profile Pic">
@endif
Use '.png' or '.jpg' as per your needs.
Upvotes: -1