I have client table and client_address info table. I need to update both table when updating client.my model classes given below,
class Client extends Model {
public function addressInfo() {
return $this->hasOne('App\Model\ClientAddressInfo');
}
}
class ClientAddressInfo extends Model {
protected $table = 'client_address_info';
public function client() {
return $this->belongsTo('App\Model\Client');
}
}
My controller for updating is given below.
$client = Client::findOrFail($id);
$client->name = rand(0, 1222222);
$address = ClientAddressInfo::where('client_id', '=', $id)->get();
$address->street = "new street";
$address->save();
But it is not working,Could you please explain the best practice for updating model and its related models.
You can do this much simpler:
$client = Client::findOrFail($id);
$client->name = rand(0, 1222222);
$client->addressInfo->street = 'new street';
$client->addressInfo->save();
$client->save();
Instead of calling save()
on both models you can also use push()
which will save the model and all it's related models:
$client = Client::findOrFail($id);
$client->name = rand(0, 1222222);
$client->addressInfo->street = 'new street';
$client->push(); // save client and addressInfo