Goal : If the file exist, load the file, else load the default.png
.
I've tried
@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
Result
It kept load my default image while I'm 100% sure that 1002.png
is exist.
How do I properly check if that file is exist ?
The disk() method receives only one parameter according to the Laravel official documentation, which is the name of the file. For example, if you want to check if a particular file exists, you just pass the name with the extension, i.e., tutorial. pdf .
The file_exists() function checks whether a file or directory exists.
The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.
You could use PHP's unlink() method just as @Khan suggested. But if you want to do it the Laravel way, use the File::delete() method instead. $files = array($file1, $file2); File::delete($files);
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 :-)
Check if file exists on action with "File::" and pass the resut to the view
$result = File::exists($myfile);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With