Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel exists()
laravel
php
communitycreator

How to check if a file exists using exists() in Laravel

Chinweuba Elijah Azubuike

Overview

One of the ways to avoid errors while working with files in your application is to first check if the file exists.

This is where the exists() method comes to play.

The exists() method returns a boolean which is used in an if statement.

Syntax

Storage::disk('s3')->exists('file.jpg');

Code explanation

In the syntax above, you will notice that the disk() method is called on the Storage facade.

For more on this, you can read my shot on how to use different disks in Laravel.

The disk() method is used to select which disk to use. By default, it uses your default disk, which is your file system to locate and store files. The exists() method is then called, chained to the disk() method, to check if the file passed exist on that particular disk.

Parameters

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.

Example

Route::get('/documemt', function () {

if(Storage::disk('s3')->exists('tutorial.pdf')){
      return Storage::download('tutorial.pdf');
}
  });

The code above checks if tutorial.pdf exists before allowing the file to be downloaded. You can search for my shot on how to use the download() method to learn how to make your site download files.

Output

The output is the prompt from your browser. In my case, I use an IDMinternet download manager to download the file.

widget

RELATED TAGS

laravel exists()
laravel
php
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring