Updating model with relationships in a single request

Published 3 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)
        '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)

    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?

3 months ago (143,050 XP)

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

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

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.