Update a table and its related model in laravel?
Asked Answered
C

2

6

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.

Cryptic answered 28/2, 2015 at 15:39 Comment(0)
L
13

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
Latia answered 28/2, 2015 at 15:44 Comment(2)
I think one day i'm going to cry with Laravel. Thanks too for the answer.Gadwall
great, How can we update the same?Loganloganberry
R
0

Also we can use mass assignment like following in the answer by @lukasgeiter:

$client = Client::findOrFail($id);
$client->fill($request->all());
$client->addressInfo->fill($request->all());
$client->push();
Russophobe answered 14/6, 2017 at 11:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.