Load Model relations from a Observer method

Viewed 221

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
2 Answers

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
}

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:

  • Attempt using the afterCommit property on your observer (I'm not sure if this will work)
  • Use an observer for the 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)
Related