Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining If a File Exists in Laravel 5

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 ?

like image 945
code-8 Avatar asked Dec 01 '15 19:12

code-8


People also ask

How to check if file exists in Laravel?

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 .

How do you check is file exist in PHP?

The file_exists() function checks whether a file or directory exists.

What is __ DIR __ In Laravel?

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.

How do you delete a file in Laravel?

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


2 Answers

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

like image 179
Lee Avatar answered Sep 22 '22 12:09

Lee


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

$result = File::exists($myfile); 
like image 40
Amancho Avatar answered Sep 21 '22 12:09

Amancho