13

With an eloquent model you can update data simply by calling

$model->update( $data );

But unfortunately this does not update the relationships.

If you want to update the relationships too you will need to assign each value manually and call push() then:

$model->name = $data['name'];
$model->relationship->description = $data['relationship']['description'];
$model->push();

Althrough this works it will become a mess if you have a lot of data to assign.

I am looging for something like

$model->push( $data ); // this should assign the data to the model like update() does but also for the relations of $model

Can somebody please help me out?

user3518571
  • 407
  • 2
  • 5
  • 11
  • 1
    There is no method for this, but have you tried something like this: `$model->relationship->fill($data['relationship']); ` then `push` ? – Jarek Tkaczyk Jun 13 '14 at 07:44
  • Thats what I currently do but I was wondering if there is a more elegant way to do so :) – user3518571 Jun 13 '14 at 07:50
  • 1
    There is no other way, as Eloquent currently doesn't know what relations are on the model until you call them as dynamic property, load with `load` method, eager load etc. (push works only with loaded relations that are present in model's `relations` array) – Jarek Tkaczyk Jun 13 '14 at 08:05

2 Answers2

16

You can implement the observer pattern to catch the "updating" eloquent's event.

First, create an observer class:

class RelationshipUpdateObserver {

    public function updating($model) {
        $data = $model->getAttributes();

        $model->relationship->fill($data['relationship']);

        $model->push();
    }

}

Then assign it to your model

class Client extends Eloquent {

    public static function boot() {

        parent::boot();

        parent::observe(new RelationshipUpdateObserver());
    }
}

And when you will call the update method, the "updating" event will be fired, so the observer will be triggered.

$client->update(array(
  "relationship" => array("foo" => "bar"),
  "username" => "baz"
));

See the laravel documentation for the full list of events.

Marius L
  • 336
  • 1
  • 7
6

You may try something like this, for example a Client model and an Address related model:

// Get the parent/Client model
$client = Client::with('address')->find($id);

// Fill and save both parent/Client and it's related model Address
$client->fill(array(...))->address->fill(array(...))->push();

There are other ways to save relation. You may check this answer for more details.

Community
  • 1
  • 1
The Alpha
  • 143,660
  • 29
  • 287
  • 307