Updating model with relationships in a single request

Published 9 months ago by falnyr

Hey there, I have a Post and Tag entities. Post can have many Tags and I want to update them in a single method like:

name = 'Foo'
random = 'Alpha'
tag[1][id] = 1
tag[1][name] = 'Bar'
tag[2][id] = 2
tag[2][name] = 'Baz'
public function update(Request $request, Post $post)
{
    $post->update([
        'name' => $request->get('name'),
        'excerpt' => $request->get('excerpt'),
    ]);

    if ($tags = $request->get('tags')) {
        foreach ($tags as $tag) {
            $tagObject = Tag::where('id', $tag['id'])
                ->where('post_id', $post->id)
                ->firstOrFail();
            $tagObject->update($tag);
        }
    }

    return $post;
}

Now this ofc. removes the excerpt (since no value was provided) and saving the tags feels a little weird - there must be a better way.

Do you know how to save only fields that were provided in request, discard the non-existing (random) and save relationships efficiently?

Dry7
Dry7
9 months ago (151,880 XP)

@falnyr https://laravel.com/docs/5.5/eloquent-relationships#inserting-and-updating-related-models try

$post->saveMany(
    collect($request->get('tags'))->map(function ($tag) { return new Tag($tag); })->toArray()
);
falnyr

Could you please reference the whole method? Even setting only the properties that were passed in the form.

Please sign in or create an account to participate in this conversation.