ihue ihue - 6 months ago 36x
PHP Question

Determining If a File Exists in Laravel 5

Goal : If the file exist, load the file, else load the


I've tried

<img src="/images/photos/account/{{Auth::user()->account_id}}.png" alt="">
<img src="/images/photos/account/default.png" alt="">


It kept load my default image while I'm 100% sure that
is exist.

How do I properly check if that file is exist ?

Lee Lee

Where ever 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 less code. You can also write a unit test on this method to test your statement as well :-)