How to Check If File Exists or Not in Laravel?

By Hardik Savani November 5, 2023 Category : Laravel

Hey Dev,

In this article, we will cover how to check file is exist or not in laravel. you will learn check file exists or not in laravel. This article goes in detailed on laravel check if image exists in storage. I would like to show you laravel check if file exists in storage.

There are several ways to check file is exist or not in laravel. i will give you following three example using Storage, File and file_exists() to check file exists or not.

So, let's see the example code:

Example 1: using Storage

In Laravel, you can use the Storage facade to check if a file exists or not. The Storage facade provides a convenient way to work with local and cloud-based storage solutions. Here's an example:

Example Code:

use Illuminate\Support\Facades\Storage;

if (Storage::exists('images/file.jpg')) {

/* File exists */

} else {

/* File doesn't exist */

}

In the above example, the exists() method of the Storagev facade is used to check if the file file.jpg exists in the images directory. If the file exists, the code inside the if block will be executed, otherwise the code inside the else block will be executed.

Example 2: using File

You can also use the File facade to check if a file exists. Here's an example:

Example Code:

use Illuminate\Support\Facades\File;

if (File::exists(public_path('images/file.jpg'))) {

/* File exists */

} else {

/* File doesn't exist */

}

Example 3: using file_exists()

You can also use the file_exists php function to check if a file exists. Here's an example:

Example Code:

if(file_exists(public_path('images/1461177230.jpg'))){

dd('File is exists.');

}else{

dd('File is not exists.');

}

i hope it can help you...

Tags :
Shares