How to check if a folder exists before creating it in laravel?
PhpLaravelLaravel 4Php Problem Overview
I need to know if a folder exists before creating it, this is because I store pictures inside and I fear that the pictures are deleted if overwrite the folder. The code I have to create a folder is as follows
$path = public_path().'/images';
File::makeDirectory($path, $mode = 0777, true, true);
how can I do it?
Php Solutions
Solution 1 - Php
See: file_exists()
Usage:
if (!file_exists($path)) {
// path does not exist
}
In Laravel:
if(!File::exists($path)) {
// path does not exist
}
> Note: In Laravel $path
start from public
folder, so if you want to check 'public/assets'
folder the $path
= 'assets'
Solution 2 - Php
With Laravel you can use:
$path = public_path().'/images';
File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
By the way, you can also put subfolders as argument in a Laravel path helper function, just like this:
$path = public_path('images/');
Solution 3 - Php
You can also call this method of File facade:
File::ensureDirectoryExists('/path/to/your/folder')
which creates a folder if it does not exist and if exists, then does nothing
Solution 4 - Php
In Laravel 5.x/6 you can do it with Storage Facade:
use Illuminate\Support\Facades\Storage;
$path = "path/to/folder/";
if(!Storage::exists($path)){
Storage::makeDirectory($path);
}
Solution 5 - Php
Way -1 :
if(!is_dir($backupLoc)) {
mkdir($backupLoc, 0755, true);
}
Way -2 :
if (!file_exists($backupLoc)) {
mkdir($backupLoc, 0755, true);
}
Way -3 :
if(!File::exists($backupLoc)) {
File::makeDirectory($backupLoc, 0755, true, true);
}
> Do not forget to use use Illuminate\Support\Facades\File;
Way -4 :
if(!File::exists($backupLoc)) {
Storage::makeDirectory($backupLoc, 0755, true, true);
}
> In this way you have to put the configuration first in config folder > filesystems.php . [Not recommended unless you are using external disks]
Solution 6 - Php
The recommended way is to use
if (!File::exists($path))
{
}
See the source code
If you look at the code, it's calling file_exists()
Solution 7 - Php
I normally create random folders inside the images for each file this helps a bit in encrypting urls and thus public will find it hardr to view your files by simply typing the url to your directory.
// Check if Logo is uploaded and file in random folder name -
if (Input::hasFile('whatever_logo'))
{
$destinationPath = 'uploads/images/' .str_random(8).'/';
$file = Input::file('whatever_logo');
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$savedPath = $destinationPath . $filename;
$this->whatever->logo = $savedPath;
$this->whatever->save();
}
// otherwise NULL the logo field in DB table.
else
{
$this->whatever->logo = NULL;
$this->whatever->save();
}