2 years ago

Updating model with relationships in a single request

Posted 2 years 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?

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