To import images from a public URL within a Laravel Filament Import action, you can indeed use the fillRecordUsing method to handle the image download and storage. Here's a step-by-step solution to achieve this:
-
Install Required Packages: Ensure you have the
guzzlehttp/guzzlepackage installed for making HTTP requests. You can install it via Composer if it's not already installed:composer require guzzlehttp/guzzle -
Create the Import Action: Define your import action and use the
fillRecordUsingmethod to handle the image download and storage. -
Download and Store the Image: Use Guzzle to download the image from the public URL and store it in your desired storage location.
Here's an example implementation:
use Filament\Actions\ImportAction;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use GuzzleHttp\Client;
class YourModelImport extends ImportAction
{
protected function fillRecordUsing(array $data): array
{
$client = new Client();
$imageUrl = $data['image_url']; // Assuming 'image_url' is the key in your import data
// Download the image
$response = $client->get($imageUrl);
$imageContents = $response->getBody()->getContents();
// Generate a unique filename
$filename = Str::random(40) . '.' . pathinfo($imageUrl, PATHINFO_EXTENSION);
// Store the image
Storage::disk('public')->put('images/' . $filename, $imageContents);
// Return the data with the stored image path
return array_merge($data, [
'image_path' => 'images/' . $filename,
]);
}
}
Explanation:
- Guzzle Client: We use Guzzle to make an HTTP GET request to the public image URL.
- Download Image: The image is downloaded and its contents are retrieved.
-
Generate Filename: A unique filename is generated using Laravel's
Str::randommethod. -
Store Image: The image is stored in the
publicdisk under theimagesdirectory. -
Return Data: The data array is returned with the added
image_pathkey, which contains the path to the stored image.
Usage:
Make sure to use this import action in your Filament resource or wherever you handle the import logic.
use App\Filament\Resources\YourModelResource;
use App\Filament\Resources\YourModelResource\Pages\YourModelImport;
class YourModelResource extends Resource
{
public static function getActions(): array
{
return [
YourModelImport::make(),
];
}
}
This should allow you to import images from public URLs and store them within your Laravel application using Filament's import actions.