Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Can't save files to public_path using storeAs

I cannot upload files to the public_path folder in Laravel 5.4. I can't understand what's going wrong, the documentation makes it look easy. $request is the POSTed contents of a form. filename is a file submitted via the form.

public function uploadFile($request) {

    if ($request->hasFile('filename') && $request->file('filename')->isValid()) {
        $file = $request->filename;

        $hash = uniqid(rand(10000,99999), true);

        $directory = public_path('files/'.$hash);

        if(File::makeDirectory($directory, 0775, true)) {
            return $file->storeAs($directory, $file->getClientOriginalName());
        }
    }

    return NULL;
}

The directory is created, but there's no file inside. As you can see, the folder has 775 permissions.

I've tried added a trailing slash. I've tried removing public_path altogether. Nothing works.

What am I doing wrong? :(

like image 283
Chuck Le Butt Avatar asked Jun 29 '17 19:06

Chuck Le Butt


1 Answers

By default file system use your default disk named 'local' that upload files in storage/app folder store using store, stroeAs etc...

The filesystem configuration file is located at config/filesystems.php.

either you can change root path under 'local'

from 'root' => storage_path('app'), to 'root' => public_path('files'),

and then in your code change from

$directory = public_path('files/'.$hash); to $directory = public_path($hash);

OR you can create new disk in config/filesystem.php

'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'my_upload' => [
            'driver' => 'local',
            'root' => public_path('files'),
            'visibility' => 'public',
        ],

and then mention new disk as below while storing file

$file->storeAs($directory, $file->getClientOriginalName(), 'my_upload');

After performing all above if not work hit below commands in order

php artisan config:clear

php artisan cache:clear

php artisan config:cache
like image 141
Ruchita Sheth Avatar answered Oct 10 '22 00:10

Ruchita Sheth