Synchro's avatar

How should I import images via artisan?

I've got image imports working nicely via an HTTP controller, as per many examples. But now I want to do the same thing to import arbitrary files from a local file system via an artisan command, where a file path is passed as an argument. In a controller I can get a handle on an uploaded file using $image = $request->file('image');, and this supports many useful things (like move(), getClientOriginalExtension()), but it seems to be specific to an uploaded file, not just a local file.

What's the right way to create an instance with similar abilities that represents a local file rather than an uploaded one?

Alternatively, how could I call my controller's store() method from artisan with the local image attached?

0 likes
3 replies
click's avatar
click
Best Answer
Level 35

You can use the following, the $path should be an absolute path to a local file.

$file = new \Illuminate\Http\File($path);
$file->move();
$file->extension();
Synchro's avatar

Oh! That's lovely and simple! Thank you.

newbie360's avatar

if your local files is outside the project folder, the easy way was create another storage disk

filesystem.php

    'disks' => [

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

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        'travel' => [
            'driver' => 'local',
            'root' => config('cfg.travel.storageRoot'),
            'url' => env('APP_URL').'/travel',
            'visibility' => 'public',
        ],

create project/config/cfg.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | My Site Config
    |--------------------------------------------------------------------------
    */
    'projectStartDate' => '2020-09-01',

    'travel' => [
        'storageRoot' => 'D:/any-path/folder',
    ],
];

create symlink

// for windows
mklink /J "D:\path-to\your-project\public\travel" "D:\any-path\folder"

// for Linux / Mac
ln -s "/path-to/your-project/public/travel" "/any-path/folder"

Please or to participate in this conversation.