Skip to content

Instantly share code, notes, and snippets.

@Braunson
Created December 21, 2017 18:21
Show Gist options
  • Save Braunson/20d2d3b3f44f81377778fed736dd93ee to your computer and use it in GitHub Desktop.
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
<?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