Search code examples
eloquentlaravel-9

Check Eloquent wasChanged on hasMany/belongsTo Model relationship


I want to check the wasChanged() status of my child/detail models, just as I do with the parent/header model in the hasMany(parent) :: belongsTo (child) relationship.

I've got code that looks like this:

$parent = Parent::updateOrCreate([ ... ], [ ... ]);
if ($parent->wasChanged()) {
    // do something useful
}
foreach ($contents as $child) {
    $parent->children()->updateOrCreate([ keys ],[ data ]);
    // Now I want to check if the Child model named Contents was changed.
    // if ($parents->children()->wasChanged()) { ...  // does not work
}

How can I accomplish this?


Solution

  • I'm not even sure this is a correct answer, but what I ended up doing and seems to be working is adding save() calls after each createOrUpdate() call. The Laravel documentation suggests this is not how it is supposed to work, but it's hard to argue with empirical evidence.

    $parent = Parent::updateOrCreate([ keys ],[ data ]);
    
    if ($header->wasChanged() || $header->wasRecentlyCreated) {
        // Do interesting work
    }
    $parent->save();
    
    foreach ($myInterestingData as $newChildData) {
        $child = $header->children()
            ->updateOrCreate( ... keys/values from $newChildData ...);
        if ($child->wasChanged() || $child->wasRecentlyCreated) {
            // Do boring work
        }
    
        $child->save();
    }