Reputation: 57
How can i load a relation from a model in an Observer?
When i try to load the relation in the created
method using $inport->load('items')
it returns an empty array.
This is the relation defined in my Inport
model:
public function items()
{
return $this->hasMany(InportItem::class);
}
Observer Method
public function created(Inport $inport)
{
dd($inport->load('items'));
}
Inport
table
id
name
inport_items
table
id
inport_id
number
Upvotes: 3
Views: 1022
Reputation: 905
The Inport observer method is triggered as soon as you call $inport->save()
or Inport::create([])
At this point, the inportItems have not been created yet. You probably do something like this on the next line: $inport->inportItems()->create([...])
So you need to:
public $afterCommit = true
$inport->save()
and your $inport->inportItems()->create([])
calls inside a DB::transaction. That way the parent observer method will be triggered AFTER the children have been created.Upvotes: 1
Reputation: 1313
The observer doesn't see the relation, because it hasn't been created yet.
The hasMany
relationship means that the InportItem
class stores the id of your Inport
model, and it can only store the id of your Inport
model after it is created.
Your options:
afterCommit
property on your observer (I'm not sure if this will work)created
event on your InportItem
model, instead of your Inport
model (you may want to add a belongsTo
on your InportItem
linking it to Inport
)Upvotes: 1
Reputation: 850
you need to try
dd( $inport->items );
and your items() method should be like.
public function items()
{
return $this->hasMany(InportItem::class, 'inport_id', 'id'); // where inport_id is your foreign key and id is your primary key in inport_items table
}
Upvotes: 1