ihue ihue - 2 years ago 164
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
Answer Source

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 :-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download