Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a table and its related model in laravel?

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.

like image 594
gsk Avatar asked Feb 28 '15 15:02

gsk


1 Answers

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
like image 61
lukasgeiter Avatar answered Nov 14 '22 21:11

lukasgeiter