29.07.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 364<br />

.<br />

1 // Create three App\User instances...<br />

2 $users = factory(App\User::class, 3)->make();<br />

3<br />

4 // Create an App\User "admin" instance...<br />

5 $user = factory(App\User::class, 'admin')->make();<br />

6<br />

7 // Create three App\User "admin" instances...<br />

8 $users = factory(App\User::class, 'admin', 3)->make();<br />

Persisting Factory Models<br />

The create method not only creates the model instances, but also saves them to the database using<br />

Eloquent’s save method:<br />

.<br />

1 public function testDatabase()<br />

2 {<br />

3 $user = factory(App\User::class)->create();<br />

4<br />

5 // Use model in tests...<br />

6 }<br />

Again, you may override attributes on the model by passing an array to the create method:<br />

.<br />

1 $user = factory(App\User::class)->create([<br />

2 'name' => 'Abigail',<br />

3 ]);<br />

Adding Relations To Models<br />

You may even persist multiple models to the database. In this example, we’ll even attach a relation to<br />

the created models. When using the create method to create multiple models, an Eloquent collection<br />

instance is returned, allowing you to use any of the convenient functions provided by the collection,<br />

such as each:

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

Saved successfully!

Ooh no, something went wrong!