DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Dave Fulton
Dave Fulton

Posted on

Creating Multiple Model Objects at Once

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]);
        $parent->children()->createMany($childNames);
    }
}

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!

Top comments (2)

Collapse
 
robhill369 profile image
robhill369

Hi Dave,

I've been searching for hints about how to solve a similar problem to this one, with not much luck. In my example, I'm not explicitly declaring children in the POST request. Instead, the POST request is sent a quantity for how many children should be created. These Children contain their own id, their parent_id, and timestamps. I'm racking my brain about how best to go about coding this all in the ParentController. Please help!

Thanks

Collapse
 
adgower profile image
Alex Gower • Edited on

from laravel docs

$post = Post::find(1);

$post->comments()->createMany([
    ['message' => 'A new comment.'],
    ['message' => 'Another new comment.'],
]);
Enter fullscreen mode Exit fullscreen mode

πŸ‘‹ Hey, my name is Noah and I’m the one who set up this ad. My job is to get you to join DEV, so if you fancy doing me a favor, I’d love for you to create an account.

If you found DEV from searching around, here are a couple of our most popular articles on DEV: