File System — Laravel 10 Discovery Training

In this new chapter we will talk about sending files and we will see how we can manage the backup of files that will be submitted by users.

The first step is to allow the user to send a file by creating a files type field in our forms and remembering to modify the attribute enctype of the form.

<form action="" method="post" class="vstack gap-2" enctype="multipart/form-data">
    <div class="form-group">
        <label for="image">Image</label>
        <input type="file" class="form-control" id="image" name="image">
    </div>
    <!-- ... -->
</form>

Then in our controller we will have to manage the file that will be submitted by the user and we will have to store it in a specific folder of our application. The file can be retrieved like any other element coming from the form.

<?php
use Illuminate\Http\UploadedFile;

class BlogController extends Controller
{

    private function create (Post $post, CreatePostRequest $request): array
    {
        $data = $request->validated();
        /** @var UploadedFile|null $image */
        $image = $request->validated('image');
        // ...
    }

Except that in the case of a file we will get something that is of type UploadedFile. On this class we have different methods that manage the processing of the file sent. In our case we will use the method store() which allows to store the file in a specific folder (with a random name).

$post->image = $image->store('blog', 'public');

In the second parameter of this method we will have to indicate the name of the disk in which we wish to save the information. Disks are used to represent different storage systems within a Laravel application and can be configured in file config/filesystems.php.

The “public” disk allows files to be stored in a folder that will be publicly accessible by users. By default, this will match the path storage/app/public. You will need to make a symbolic link to make this folder accessible.

php artisan storage:link

In addition to this way of managing the files sent, we have the possibility of using a facade to be able to carry out different operations on the files such as deletion or renaming. For example in our case we may want to delete the image that would previously have been sent by the user during an update.

use Illuminate\Support\Facades\Storage;

if ($post->image) {
    Storage::disk('public')->delete($post->image);
}