Reputation: 7725
I have a model Image
and a model Metadata
. Metadata
can belong to Image
, but it can also belong to other models, so I use a polymorphic relation:
Image.php:
public function metadata()
{
return $this->morphMany('App\Metadata', 'content');
}
Metadata.php:
public function content()
{
return $this->morphTo();
}
public function setAuthorAttribute($value)
{
$this->attributes['author'] = strtoupper($value);
}
When I want to create an image with its metadata, which looks like this:
["author" => "Foo Bar"]
I use this code:
$image = Image::create($request);
$image->metadata()->create($this->mapMetadata($request));
This works well. But when I try to update an image with its metadata, with this code:
$image = Image::findOrFail($id);
$image->update($request);
$image->metadata()->update($this->mapMetadata($request));
The data is updated, but my mutator is ignored. In other words, when creating, the author
is turned to uppercase, but when updating, it's not.
EDIT: Migration for Metadata table:
$table->increments('id');
$table->string('author')->nullable();
$table->unsignedInteger('content_id');
$table->string('content_type');
Upvotes: 1
Views: 450