Spread the love

This article will guide you to Check folder exist and Create Nested Folder in Laravel. To perform the file system based operations like Check folder exist and Create a Nested Folder. we use File class in laravel. Laravel provides inbuilt library to access the file system and we can do multiple robust operations using the libraries. In this tutorial i will show you to make a directory in laravel and also i will show you to create nested folder in using the library. If we perform same operations using the core php functions than it can be a hectic or lengthy code to implement but using the packages or library it will be easier to implement.

In this article I will use Illuminate\Filesystem\Filesystem class and facade File::makeDirectory() method to create the new directory in the folder. makeDirectory Method accepts four parameters as below

File::makeDirectory($path, $mode, $recursive, $force)

Example Usage:

File::makeDirectory(public("images/user/1"), 0777, true);

Here I called makeDirectory with 3 parameters first parameter tells to create the nested folder as images > user > 1, second parameter for permission of the folder and third for creating the recursive folders so in nutshell

$path : Path of directory to create.

$mode : Permission of folders

$recursive : Create directory recursively

$force : To create directory forcefully

Let’s understand it with example step by step

Step 1: Create a fresh laravel project

Open a terminal window and type below command to create a new project

composer create-project --prefer-dist laravel/laravel blog

You can also read this to start with new project

Step 2 : Create controller

Let’s create a controller and add method checkAndCreateDirectory

php artisan make:controller FolderController

and add the below code


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use File;
class FolderController extends Controller
    public function checkAndCreateDirectory(Request $request){
            if (!File::exists( $storageDestinationPath)) {
                File::makeDirectory($storageDestinationPath, 0755, true);
            return response("Folder created successfully");

In above code First of all we are checking the directory is exist or not then if not available then we are creating the directory at the location.

Step 3: Create two routes in routes/web.php

Create a route to create the directory



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


Leave a Reply