06.10.2016 Views

laravel-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Testing 480<br />

1 $users = factory(App\User::class, 3)<br />

2 ->create()<br />

3 ->each(function ($u) {<br />

4 $u->posts()->save(factory(App\Post::class)->make());<br />

5 });<br />

Relations & Attribute Closures<br />

You may also attach relationships to models using Closure attributes in your factory definitions. For<br />

example, if you would like to create a new User instance when creating a Post, you may do the<br />

following:<br />

1 $factory->define(App\Post::class, function ($faker) {<br />

2 return [<br />

3 'title' => $faker->title,<br />

4 'content' => $faker->paragraph,<br />

5 'user_id' => function () {<br />

6 return factory(App\User::class)->create()->id;<br />

7 }<br />

8 ];<br />

9 });<br />

These Closures also receive the evaluated attribute array of the factory that contains them:<br />

1 $factory->define(App\Post::class, function ($faker) {<br />

2 return [<br />

3 'title' => $faker->title,<br />

4 'content' => $faker->paragraph,<br />

5 'user_id' => function () {<br />

6 return factory(App\User::class)->create()->id;<br />

7 },<br />

8 'user_type' => function (array $post) {<br />

9 return App\User::find($post['user_id'])->type;<br />

10 }<br />

11 ];<br />

12 });

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!