Laravel 5.5 Model Factories

Laravel 5.5 Model Factories

Laravel is a fully fledged php framework which helps the developer for rapid application development. This framework has amazing built-in features for development, testing and deployment. The unit testing phase is really cumbersome in some projects. Sometimes, it eats our valuable time exceeding the development time frames. Therefore, as developers we should think of automating our testing steps, test driven development and other well planned testing techniques. Before start testing, it is better to have some testing data in a persistent storage.

In the past we used third party tools to generate testing data sets. Tools like Mockaroo can generate random fake data. This will be suitable for a small application when there’re one or two tables. It will be difficult to handle to large application with such tools. The reason is there is no easy integration with the testing data generator with our application. It is not part of the project and we have to maintain this layer externally or adopt it to our project after some additional customizations.

Laravel fills the gap! Laravel comes with built-in test data generators with Eloquent support. With a tinker command, it is possible to generate large amount of data sets with no time. In this tutorial, we will see how to use model factories to get some test data.

First it needs to create a factory for the eloquent model. If you navigate to database/factories in a fresh Laravel installation, you can see a generated UserFactory class. In previous Laravel versions, all factories were kept in a single file which is not good in maintenance aspect. In Laravel 5.5, it is possible to separate factory per model.

Create a factory with below artisan command.

php artisan make:factory PostFactory --model=Post

Optional argument with model name can be set here. This command will create a new factory in the same folder.

Write the factory with specifying default columns in  database table you need to populate.

use Faker\Generator as Faker;

$factory->define(App\Post::class, function (Faker $faker) {
    return [

        'name' => $faker->name,
        'body' => $faker->text

It uses Faker library to generate different  data types. Please check the github repository to see a full list of data types you can use.

Now you can call factory() with providing the Eloquent model and records count to generate.

factory(App\Post::class, 300)->create()

This will generate and persist data set. Similarly, you can create different factories according to your testing requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *