ictoplossing's avatar

How to update any table from another model?

Hello,

I have some Contact (table "person") with multiple coupled Companies (table "person_addresses" with foreign keys "person_id" and "address_id").

ID,person_id,address_id
229,261,100
240,262,86
241,262,54

PersonController.php:

public function store(StorePersonRequest $request)
    {
	if ($request->person_address) {
            foreach ($request->person_address as $key => $value) {
                PersonAddress::create([
                    'person_id' => $person->id,
                    'address_id' => $value
                ]);
            }
        }
    }

How to update/remove rows from the table "person_addresses" if I a view person.edit have selected some new addresses but unselected some old adresses?

Tnx!

0 likes
5 replies
ousid's avatar
ousid
Best Answer
Level 3

It seems you are using povit table to link the person with addresses.

Actually, you need to provide more details

  • Do you have an Address model?
  • Do you have any relationship between the Person & the Address model?

Assuming you have an Address model to store the addresses, you may use the following approach.

In your Person.php Model

public function addresses()
{
   return $this->belongsToMany(Address::class);
}

In your Controller:

public function store(StorePersonRequest $request)
{
   $person = Person::find($request->person_id);

   $person->addresses()->attach($request->person_address) // assuming the "person_address" returns an array

   return redirect()->route(...); // or whatever what you want to return.
}

// on the update method
public function update(UpdatePersonRequest $request, Person $person)
{
   // if you want to add new values (override the old values)
   $person->addresses()->sync($request->address); // assuming the request returns an array of values.

  // if you want to add new values without overriding the old ones
  $person->addresses()->syncWithoutDetaching($request->address);
}

PS: This answer is not tested, you may find problems, let me know if you have any questions.

1 like

Please or to participate in this conversation.