Created
December 21, 2017 18:21
-
-
Save Braunson/20d2d3b3f44f81377778fed736dd93ee to your computer and use it in GitHub Desktop.
Need to loop through multiple Laravel models to do the same update on all of their results? In this example it's updating the address country id
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Models to run through | |
$models = collect([ | |
'contact', | |
'business', | |
]); | |
// Loop through the models | |
$models->each(function ($value, $key) use ($keys) { | |
// Put together the namespace | |
$model = 'App\\Models\\' . ucwords($value); | |
// Get any result with country_id = 1 | |
$model = $model::where('country_id', 1)->get(); | |
// We have results? | |
if ($model->count()) { | |
// Loop through each result | |
$model->each(function($child, $key) { | |
$child->country_id = 2; | |
$child->save(); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment