Updating model with relationships in a single request

Posted 11 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?

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

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.