3 Ways to Check File Exist or Not in Laravel – Quick Guide

March 5, 2023
Laravel
3 Ways to Check File Exist or Not in Laravel – Quick Guide

In this guide, you will learn 3 ways of checking whether the file exists or not in laravel. We will not only discuss the ways of checking file exist or not in public directory but also share examples of it.

Let’s get started!

Method 1: Using File::exists checks whether file exist or not

In this method, we will using laravel file() method exists, in order to check whether file exists or not. Add the following code in the controller:

public function index()
   {
	  if (File::exists(public_path('path/file-name.png')))
		echo 'File Exists';
	 else echo 'File Doesn't Exists';
   }

In the above code, we are using File::exists method in order to check whether the file is present or not. File::exists return true if files exist and false, in case the file doesn’t exist.

In the method argument, we have passed the full file path, which in this case we are getting using public_path.

Method 2: Using Storage::exists checks whether file exist or not

In this particular method, we will using Storage::exists which works same as File::exists discussed in the previous method. Here is what you need to add to the controller:

public function index()
   {
	  if (Storage::exists(public_path('path/file-name.png')))
		echo 'File Exists';
	 else echo 'File Doesn't Exists';
   }

Similar to File::exists , Storage::exists returns true if the file exists and returns false it doesn’t exist.

Method 3: Using PHP native file_exists function to check whether file exist or not

In this last method, we will be using PHP native function file_exists function to check whether the file exists in the directory or not. Here is the following code, you need to add to the controller:

public function index()
   {
	  if (file_exists(public_path('path/file-name.png')))
		echo 'File Exists';
	 else echo 'File Doesn't Exists';
   }

In the above code, we are using file_exists method, that will allows to check whether file exists or not. If the file doesn’t exist in the directory, it will return false and if exists it will return true.

Conclusion

In the above article, we have discussed 3 ways of checking whether file exists in the directory or not in laravel application. We have discussed each method in detail with the code.

Let me know if you have any questions, I will see you in the next one 🙂

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon