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.
Storage::disk('s3')->exists('file.jpg');
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.
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
.
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.
The output is the prompt from your browser. In my case, I use an