kingsleyuchenna's avatar

Updating Parent with child or children relationship

I have a project with admin_users table. A user can be assigned to be an author which is another table admin_authors.

I have another table called social_handles actually is a morph table. Admin authors can have social handles, is there a way to create or update all these tables in the same form?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

Yes, you can use Laravel's nested relationships to create or update all these tables in the same form. Here's an example:

Assuming you have the following relationships:

  • AdminUser has one AdminAuthor
  • AdminAuthor has many SocialHandle

You can create a form that includes fields for all three models, and use Laravel's updateOrCreate method to update or create the records as needed.

Here's an example of how you could handle the form submission in your controller:

public function update(Request $request, AdminUser $adminUser)
{
    $adminUser->update($request->only(['name', 'email']));

    $adminAuthorData = $request->only(['bio', 'website']);
    $adminAuthor = $adminUser->adminAuthor()->updateOrCreate([], $adminAuthorData);

    $socialHandlesData = $request->input('social_handles', []);
    $socialHandles = collect($socialHandlesData)->map(function ($data) {
        return new SocialHandle($data);
    });
    $adminAuthor->socialHandles()->saveMany($socialHandles);

    return redirect()->back();
}

In this example, we first update the AdminUser record with the data from the form. Then, we use updateOrCreate to update or create the AdminAuthor record with the data from the form.

Finally, we loop through the social_handles data from the form, create new SocialHandle models for each one, and save them to the AdminAuthor's socialHandles relationship.

Note that this is just one example of how you could handle this. Depending on your specific requirements, you may need to adjust the code to fit your needs.

1 like

Please or to participate in this conversation.