Upload multiple images to a model

I have a Project model and I want the user to be able to upload many images for each project. I'm storing the images in an images table.
class Project extends Model
{
protected $casts = [
'images' => 'array',
];

public function images(): MorphMany
{
return $this->morphMany(Image::class, 'imageable');
}
}
class Project extends Model
{
protected $casts = [
'images' => 'array',
];

public function images(): MorphMany
{
return $this->morphMany(Image::class, 'imageable');
}
}
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('url');
$table->unsignedBigInteger('imageable_id');
$table->string('imageable_type');
$table->timestamps();
});
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('url');
$table->unsignedBigInteger('imageable_id');
$table->string('imageable_type');
$table->timestamps();
});
How do I allow the user to upload images and have them associated to the Project model being created?
FileUpload::make('images')
->image()
->multiple()
->maxFiles(10)
->reorderable(),
FileUpload::make('images')
->image()
->multiple()
->maxFiles(10)
->reorderable(),
Solution:
If you use multiple() Filament expects the file paths to be saved in a json array on the model. If you want to use a morph relationship, you will want to use a relation manager or write some custom logic that will use the array, create and attach the related models, unset the data on the original model, etc.
Jump to solution
2 Replies
Solution
Tim van Heugten
Tim van Heugten13mo ago
If you use multiple() Filament expects the file paths to be saved in a json array on the model. If you want to use a morph relationship, you will want to use a relation manager or write some custom logic that will use the array, create and attach the related models, unset the data on the original model, etc.
@nasilemak
@nasilemakOP13mo ago
Thanks Tim. I refactored my code to simply add an images json column to my projects table. That did the trick. 👌

Did you find this page helpful?