mardi 17 janvier 2017

Saving both polymorphic relationship at the same time in Laravel 5.3

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();
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2iKIh0k
via IFTTT

Aucun commentaire:

Enregistrer un commentaire