Hammadr097
Hammadr097

Reputation: 81

Laravel 5.6:Check if a file exists

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:

  1. The file exists in a path outside of storage. (it exists in public folder)

  2. 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

Answers (2)

Tpojka
Tpojka

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

Sabyasachi Patra
Sabyasachi Patra

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

Related Questions