Laravel: Сериализация 'Illuminate \ Http \ UploadedFile' не разрешена - PullRequest
0 голосов
/ 28 мая 2019

Я пытаюсь загрузить изображение, сохранить его на диске и добавить путь к файлу JSON, который хранится в базе данных. каждый пользователь получил файл JSON со всеми своими изображениями, такими как:

{"images": ["/vendors/57/horse-11.png", "/vendors/57/horse-11.png"]}

Этот JSON-файл хранится в базе данных в столбце 'images'.

Я борюсь с этой проблемой в течение нескольких дней. Я всегда получаю следующее исключение:

Serialization of 'Illuminate\Http\UploadedFile' is not allowed

ошибка возникает в этой части кода из функции processImage:

$image = Image::make($request->file('image'))
                ->resize(750, null, function ($constraint) {
                    $constraint->aspectRatio();
                })
                ->encode('png');

Я проведу вас через процесс:

Сначала пользователь загружает изображение, код:

https://codeshare.io/jGzQ9

во-вторых, черезways.php контроллер называется:

public function update(User $user, UserHouse $house, UserHouseRequest $request){
    $path = $this->processImage($request, $user->id, $house->id);
    $jsonstring = $house->images;
    array_push($jsonstring['images'], $path);

    $house->images = $jsonstring;
    $house->save();

    return back();
}

private function processImage($request, $userId, $houseId)
{
    $path = null;
    $number = rand(1, 99);
    if ($request->hasFile('image')) {
        $image = Image::make($request->file('image'))
            ->resize(750, null, function ($constraint) {
                $constraint->aspectRatio();
            })
            ->encode('png');
        $path = "/users/{$userId}/house-{$houseId}-{$number}.png";
        Storage::disk('fileadmin')->put($path, $image->encoded);
    }

    return $path;
}

Существует также некоторый код JS, но я думаю, что это не является необходимым для этой проблемы. Если это произойдет, я добавлю это позже.

Я использую Laravel 5.5

StackTrace:

2019-05-28 13:30:49] local.ERROR: Serialization of 'Illuminate\Http\UploadedFile' is not allowed {"userId":57,"email":"info@ho.com","exception":"[object] (Exception(code: 0): Serialization of 'Illuminate\\Http\\UploadedFile' is not allowed at /Users/sg/ah-website/user/laravel/framework/src/Illuminate/Session/Store.php:128)
[stacktrace]
#0 /Users/sg/website/user/laravel/framework/src/Illuminate/Session/Store.php(128): serialize(Array)
#1 /Users/sg/website/user/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(87): Illuminate\\Session\\Store->save()
#2 /Users/sg/website/user/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(218): Illuminate\\Session\\Middleware\\StartSession->terminate(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Response))
#3 /Users/sg/website/user/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(189): Illuminate\\Foundation\\Http\\Kernel->terminateMiddleware(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Response))
#4 /Users/sg/website/public/index.php(60): Illuminate\\Foundation\\Http\\Kernel->terminate(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Response))
#5 /Users/sg/website/server.php(21): require_once('/Users/sg...')
#6 {main}
"} 

конфиг / filesystems.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. The "local" disk, as well as a variety of cloud
    | based disks are available to your application. Just store away!
    |
    */

    'default' => env('FILESYSTEM_DRIVER', 'local'),

    /*
    |--------------------------------------------------------------------------
    | Default Cloud Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Many applications store files both locally and in the cloud. For this
    | reason, you may specify a default "cloud" driver here. This driver
    | will be bound as the Cloud disk implementation in the container.
    |
    */

    'cloud' => env('FILESYSTEM_CLOUD', 's3'),

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been setup for each driver as an example of the required options.
    |
    | Supported Drivers: "local", "ftp", "s3", "rackspace"
    |
    */

    'disks' => [

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

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

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_KEY'),
            'secret' => env('AWS_SECRET'),
            'region' => env('AWS_REGION'),
            'bucket' => env('AWS_BUCKET'),
        ],

        'fileadmin' => [
            'driver' => 'local',
            'root' => public_path(),
            'visibility' => 'public',
            'url' => config('app.url'),
        ],
    ],

];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...