Laravel 8: using Facades within Closures

407 Views Asked by At

I'm using spatie/async to do async uploading of photos to AWS S3. I'm trying to use some facades from within the closures. For example:

foreach ($images as $image) {
    ...

    $pool->add(function () use ($encodedImage, $previewImage, $post, $extension, $realPath, $pictureCount) {
            $resizedImage = Image::make($realPath)->fit(400, 400);
            ...
            Storage::disk('s3')->put($file_path, $resizedImage->__toString(), ['visibility' => 'public']);
            ...
            return $file_path;
        })->then(function ($s3Path) use ($s3Urls) {
            ...
        })->catch(function (Throwable $exception) {
            throw $exception;
        });
    }
    ...
}

It fails, and I receive the following error in my storage/logs/laravel.log file:

[2020-12-11 03:32:06] local.ERROR: A facade root has not been set.

#0 closure://function () use ($encodedImage, $previewImage, $post, $extension, $realPath, $pictureCount) {
                $resizedImage = \Intervention\Image\Facades\Image::make($realPath)->fit(400, 400);
...

I've seen some answers regarding "A facade root has not been set.", and it seems like the solution in some cases is to uncomment $app->withFacades(); in bootstrap/app.php - however, I don't have that in app.php, and trying to add it results in Call to undefined method Illuminate\Foundation\Application::withFacades().

I'm guessing I get this error because, within the closure, Laravel can't resolve \Intervention\Image\Facades\Image? How can I fix this, or is using facades in closures not supported?

Edit: to clarify, I can use this Image facade without any issues outside of the closure.

0

There are 0 best solutions below