DEV Community


Creating Multiple Model Objects at Once

thedavefulton profile image Dave Fulton ・2 min read

Disclaimer - I'm still fairly new to Laravel, so I'll readily admit that there may be other/better ways of doing this, or that this is already well known. But a bit of Googling seemed to indicate otherwise

So today I was presented with a bit of a challenge. I have a parent object that I'll creatively call "App\Parent" which has a bunch of children I'll call, um, "App\Child"?

Yeah, that works.

So the children are basically just a bunch of filenames, and the POST request already has them put into an array, so I'd like to just stick that array in some kind of Model::Create() method, but Create() seems to prefer just one set of attributes, thank you very much.

Some looking around found a solution in using the Insert() method. This would allow me to insert as many records as I wanted but apparently wouldn't set the timestamps. And I don't want to do that manually. Or rather, I don't want to waste the server's time doing it manually.

And that's when I stumbled onto the solution. If you have a HasMany relationship, you can use the CreateMany() method on that. Let me give you an example. Say I have a couple of basic Models that are related with a HasMany/BelongsTo.

class Parent extends Model
    public function children()
        return $this->hasMany('App\Child');

class Child extends Model
    public function parent()
        return $this->belongsTo('App\Parent');

I can leverage that relationship to create all the children I want in one shot. Let's say I get a request with 'parentName' and an array of 'childNames'. I can handle it like so:

class ParentController extends Controller
    public function store(Request $request)
        $parentName = $request->get('parentName');
        $childNames = $request->get('childNames');
        // Remember, $childNames is already an array

        $parent = Parent::create(['parent_name' => $parentName]);

That's it. And a little bonus feature is that you don't even have to pass in the 'parent_id' as an attribute; it's handled automatically. As I said before, this may all be common knowledge, but if it's not, I want this to at least be easier to find for the next person!

Happy Hacking!

Discussion (0)

Editor guide