Determining If a File Exists in Laravel 5

Check if file exists on action with "File::" and pass the resut to the view

$result = File::exists($myfile);

Solution

      @if(file_exists( public_path().'/images/photos/account/'.Auth::user()->account_id.'.png' ))
        <img src="/images/photos/account/{{Auth::user()->account_id}}.png" alt="">
      @else
        <img src="/images/photos/account/default.png" alt="">
      @endif

Wherever you can, try and reduce the number of if statements. For example, I would do the following:

// User Model
public function photo()
{
    if (file_exists( public_path() . '/images/photos/account/' . $this->account_id . '.png')) {
        return '/images/photos/account/' . $this->account_id .'.png';
    } else {
        return '/images/photos/account/default.png';
    }     
}

// Blade Template
<img src="{!! Auth::user()->photo() !!}" alt="">

Makes your template cleaner and uses less code. You can also write a unit test on this method to test your statement as well :-)


In Laravel 5.5, you can use the exists method on the storage facade:

https://laravel.com/docs/5.5/filesystem

$exists = Storage::disk('s3')->exists('file.jpg');

You could use a ternary expression:

$file = ($exists) ? Storage::disk('s3')->get('file.jpg') : 
         Storage::disk('s3')->get('default.jpg');