Last updated on December 29, 2022
In the latest release of the Laravel framework (Laravel 9.30), Frank de Jonge added a scoped filesystem driver that helps to reuse the disk configurations. In this article, we will be using the newly added scoped filesystem driver.
Let’s suppose we want to keep the images and videos in separate folders which is better than keeping all files in one folder.
When you install a fresh Laravel application, you will get the below public array in the filesystems.php
file that is located in the config directory. It is a child array of disks.
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
],
Before scoped filesystem driver feature, we were duplicating the public disk to keep the file in a separate folder. But in the latest version of Laravel we can use the same disk with different directories through the scoped filesystem driver.
According to Frank de Jonge, we can add a new child array into the disks array.
'public_videos' => [
'driver' => 'scoped',
'prefix' => 'videos',
'disk' => 'public',
],
In the above array, we have three key value items. Following are the detail for each item,
driver
: it’s value is scoped which means it follows the disk.prefix
: path of the filedisk
: disk name that needs to be followed.The parent key of the above array is public_videos
. In this key public comes from public disk because it will be working under public disk configurations and it is good for understanding. Similarly, let’s add one more array for images.
'public_images' => [
'driver' => 'scoped',
'prefix' => 'images',
'disk' => 'public',
],
Now let’s use it.
1. Upload File to Public Disk
Storage::disk('public')->put('any-file.txt', 'public folder text');
Above code uploads file into storage/app/public
directory.
2. Upload File to Public Videos Disk
Storage::disk('public_videos')->put('any-file.txt', 'video folder text');
Above code creates videos
directory into storage/app/public
and uploads file into it.
3. Upload File to Public Images Disk
Storage::disk('public_images')->put('any-file.txt', 'image folder text');
Above code creates images
directory into storage/app/public
and uploads file into it.
In this article, we have learned how the scoped filesystem driver helps to reuse disk configurations. If you would like to learn more about Laravel, check out our Laravel page.