I want to correctly save both polymorphic relationships at the same time. The code below works, but I feel it could be a lot cleaner as I presume the two update()
methods are calling the database twice.
A NewsModule::class
can have different module items; VideoModule
, TextModule
, ImageModule
, and a few more. Each containing their own content to be attached to the parent NewsModule
.
As mentioned, the code works so the relationships are set up correctly, but I'm convinced there's a cleaner way of saving both at the same time.
I'm also open to suggestions about cleaning up the if
statements too. But maybe that's another post.
public function update(Request $request, $id)
{
$module = NewsModule::find($id);
if ($module->type === 'text') {
$content = TextModule::find($module->content_id);
} elseif ($module->type === 'image') {
$content = ImageModule::find($module->content_id);
};
$module->update($request->all());
$content->update($request->all());
return fractal()
->item($module, new NewsModuleTransformer)
->parseIncludes(['content'])
->toArray();
}
Updated (more code by request)...
Structure:
news_modules
- id
- content_id
- content_type
- etc
text_modules
- id
- content
- etc
image_modules
- id
- image_id
- etc
NewsModule:
class NewsModule extends Model
{
public function content()
{
return $this->morphTo();
}
}
All item modules:
class TextModule extends Model
{
public function newsmodules()
{
return $this->morphMany(NewsModule::class, 'content');
}
}