DevBlog

Coding my way

11 months ago in PHP, Laravel · 1 MIN READ

Laravel Model factories and complex relations

My guess that if you are searching for this, you already have a grasp on what Model factories can do for you during development and/or testing.

Last time I've stuck on how to create complex factories, that I can create seeds for my more complex models.

You are probably already familiar with this in your database/factories/ModelFactory.php file:

$factory->define(App\Post::class, function (Faker\Generator $faker) {
    return [
        'title' => $faker->words(5,true),
        'content' => '<p>' . $faker->sentence() . '</p>'
    ];
});

Great, We can generate posts! Huzzaaah! But wait, posts usually have comments, right?! Crap, how do I get comments in there?

EASY!

Just create your comment factory, and we'll head over to the seeds!

You should already have something like this:

<?php

use Illuminate\Database\Seeder;

class PostSeed extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Post::class,30)->create();
    }
}

It's time to take this one step further and attach some comments:

public function run() 
{
  factory(App\Post::class,30)->create()->each(function(App\Post $post) {
    $post->comments()->saveMany(factory(App\Comment::class,40)->create());
  });
}

And there you have it! Now each generated post has 40 comments attached with the power of Eloquent and Model factories. Inside the each() method, the $post behaves as a normal model, so you can use this other ways as well, like attaching generated media, or general manipulation.

···

Miklós Galicz

I'm a hobbyist who managed to become a professional web developer who specializes in Laravel and Vue.js, also the Spice must flow.
comments powered by Disqus


© 2017 DevBlog