Check For File Existence in Public Folder in Laravel

Nov 28, 2022 . Admin



Hello Friends,

In this tutorial, I will show you the check for file existence in a public folder in laravel. This tutorial will give you a simple example of laravel check if a file exists in the public folder with example. step-by-step explanation and check the existence of a file in a public folder in laravel. This post will give you a simple example of how to check if a file exists in a public folder in laravel. You need to do a laravel check if a file exists in the public folder.

You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.

You have to follow the below step and you will get the layout as below:

Step 1: Install Laravel

This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app
Step 2: Create Format Route web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PublicFileExistsController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/index',[PublicFileExistsController::class, 'index']);
Step 3: create PublicFileExistsController

we will create PublicFileExistsController. so you can see the below code with output:

php artisan make:controller PublicFileExistsController
App\Http\Controllers\PublicFileExistsController
<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class PublicFileExistsController extends Controller
{
    
    /**
     * The attributes that are mass assignable.
     *
     * @var array
    */
    public function index()
    {
        
        if(file_exists(public_path('/images/demo'))) {

            dd('exists');  

        }else{

            dd('not exists');
        
        }
    }
}
Step 4: Start Development Server

Start the development server. Use the PHP artisan serve command and start your server:

php artisan serve

Now you are ready to run our example so run the below command to quick run.

http://localhost:8000/index
Output:
"exists" // app/Http/Controllers/PublicFileExistsController.php:18

I hope it can help you...

#Laravel