Scott Cottam

scott@scottcottam.co.uk

Laravel: Uploading Directly To The Public Folder

18th June, 2021

I have to admit uploading an image directly the public directory using Laravel stumped me for longer than I would have liked as the Laravel documentation isn’t exactly forthcoming for a scenario in which this would be required.

For the uninformed the Laravel documentation would much prefer you to upload files into the Storage directory and create a symlink between the files within the Storage directory and the Public directory, this symlink is created using the Artisan command line interface, this method works great within the development environment of Homestead and any hosting that allows you to have complete access to shell interface, however on shared hosting this may not always be the case. 

There are workarounds for this however as Artisan commands can be called programmatically, a solution highlighted on Stack Overflow is to create a route that when visited calls the Artisan command to create the symlink, this did not work for me but it may work for others.

The solution that ultimately worked for me is from another post of Stack Overflow and is the second result on Google for this very problem, the post calls for a new storage disk to be created within config/filesystems.php that points to the Public directory and then specifying the new storage disk when the Storage class is called using the Disk method.

Below is my interpretation of the solution highlighted in the previous section.

File System Config

Within config/filesystems.php

        'direct_upload' => [
            'driver' => 'local',
            'root'   => public_path(),
        ]

This config creates a new disk that points to the base directory of the public path.

Usage

Storage::disk('direct_upload')->putFileAs('directory',$file,$file->getClientOriginalName());

The disk method selects the new ‘direct_upload’ disk and the putFileAs method uploads the file, this method has three options the first specifies the directory the uploaded file is being stored in, for this example it is just ‘directory’ but in a real world scenario it would be something like ‘img’ or ‘file’. The second option is the file that is being uploaded, this is usually from a request and the third option is what the name of the uploaded file is to be, in this case the getClientOriginalName() function keeps the original file name of the uploaded file as it is stored, this could be changed to something else entirely but for my use the original name of the file is most optimal. 

Tags: laravel