Generate Laravel test factories from your existing models

Last update: May 15, 2022

Laravel Test Factory Generator

php artisan generate:model-factory

This package will generate factories from your existing models so you can get started with testing your Laravel application more quickly.

Example output

Migration and Model

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('username');
    $table->string('email')->unique();
    $table->string('password', 60);
    $table->integer('company_id');
    $table->rememberToken();
    $table->timestamps();
});

class User extends Model {
    public function company()
    {
        return $this->belongsTo(Company::class);
    }
}

Factory Result

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'username' => $faker->userName,
        'email' => $faker->safeEmail,
        'password' => bcrypt($faker->password),
        'company_id' => factory(App\Company::class),
        'remember_token' => Str::random(10),
    ];
});

Install

Require this package with composer using the following command:

composer require --dev mpociot/laravel-test-factory-helper

Usage

To generate multiple factories at once, run the artisan command:

php artisan generate:model-factory

This command will find all models within your application and create test factories. By default, this will not overwrite any existing model factories. You can force overwriting existing model factories by using the --force option.

To generate a factory for specific model or models, run the artisan command:

php artisan generate:model-factory User Team

By default, this command will search under the app folder for models. If your models are within a different folder, for example app/Models, you can specify this using --dir option. In this case, run the artisan command:

php artisan generate:model-factory --dir app/Models -- User Team

License

The Laravel Test Factory Helper is free software licensed under the MIT license.

GitHub

https://github.com/mpociot/laravel-test-factory-helper
Comments
  • 1. Installation fails with an error

    I have tried to install this package (on a fresh Laravel 5.2.27 installation) using composer require, but I get an error:

    [Symfony\Component\Debug\Exception\FatalErrorException]
    Class 'Mpociot\LaravelTestFactoryHelper\TestFactoryHelperServiceProvider' not found
    
    Script php artisan optimize handling the post-update-cmd event returned with an error
    
    Installation failed, reverting ./composer.json to its original content.
    
    [RuntimeException]
    Error Output:
    

    the same happens when I run php artisan test-factory-helper:generate

    [Symfony\Component\Debug\Exception\FatalErrorException]
    
    Class 'Mpociot\LaravelTestFactoryHelper\TestFactoryHelperServiceProvider' not found
    
    Reviewed by nunomira at 2016-03-29 16:02
  • 2. Allow override relations columns

    It allows to override value without creating another model instance. It works like a closure

    'user_id' => function () {
                return factory(App\User::class)->create()->id;
            }
    
    Reviewed by markinigor at 2019-06-22 19:13
  • 3. Allow "enum" type

    Instead of just mapping enum type fields to act as "string", I created a custom type. This way a MySQL field like this:

    size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
    

    will produce a factory like this:

    ...
    'size' => $faker->randomElement(['x-small','small','medium','large','x-large']),
    ...
    
    Reviewed by skeets23 at 2019-11-29 04:53
  • 4. Not Support in laravel 5.4

    Problem - mpociot/laravel-test-factory-helper 0.3.1 requires illuminate/support 5.0.x|5.1.x|5.2.x|5.3.x and - mpociot/laravel-test-factory-helper 0.3.1 requires illuminate/filesystem 5.0.x|5.1.x|5.2.x|5.3.x don't install laravel/framework v5.4.0

    Reviewed by ghost at 2017-01-24 21:58
  • 5. Not working on laravel 5.3

    Problem 1 - Installation request for mpociot/laravel-test-factory-helper ^0.2.1 -> satisfiable by mpociot/laravel-test-factory-helper[0.2.1]. - Conclusion: remove laravel/framework 5.3.x-dev - mpociot/laravel-test-factory-helper 0.2.1 requires illuminate/filesystem 5.0.x|5.1.x|5.2.x -> satisfiable by laravel/framework[5.2.x-dev], illuminate/filesystem[5.0.x-dev, 5.1.x-dev, 5.2.x-dev, v5.0.0, v5.0.22, v5.0.25, v5.0.26, v5.0.28, v5.0.33, v5.0.4, v5.1.1, v5.1.13, v5.1.16, v5.1.2, v5.1.20, v5.1.22, v5.1.25, v5.1.28, v5.1.30, v5.1.31, v5.1.6, v5.1.8, v5.2.0, v5.2.19, v5.2.21, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.31, v5.2.32, v5.2.37, v5.2.6, v5.2.7]. - Can only install one of: laravel/framework[5.3.x-dev, 5.2.x-dev]. - don't install illuminate/filesystem 5.2.x-dev|don't install laravel/framework 5.3.x-dev

    Reviewed by dieg0 at 2016-08-04 16:55
  • 6. Update and streamline package for common use case

    Several changes in this, hope you don't mind. Mainly, set the minimum requirement of Laravel 5.5. This allowed removal of PHP < 7 syntax, old references and helpers, and deprecated Symfony methods.

    Also did a general scouting of the code which lead to removal of not-so-often used options to help focus the commands purpose.

    Finally a rename to provide symmetry with generate commands offered in other packages.

    Reviewed by jasonmccreary at 2019-06-18 18:35
  • 7. Non-functioning in Laravel 5.5

    Reviewed by AlbinoDrought at 2017-09-14 22:32
  • 8. Use PSR-4 autoloading

    Was trying this out and as seen in issue #1, I could not install successfully without receiving:

    [Symfony\Component\Debug\Exception\FatalErrorException]
    
    Class 'Mpociot\LaravelTestFactoryHelper\TestFactoryHelperServiceProvider' not found
    

    Here's what I did to get it working for me.

    • Changed autoloading to PSR-4.
    • Temporarily removed Mpociot\LaravelTestFactoryHelper\TestFactoryHelperServiceProvider from config/app.php
    • composer dumpauto -o
    • php artisan optimize && php artisan clear-compiled
    • Added Mpociot\LaravelTestFactoryHelper\TestFactoryHelperServiceProvider back to config/app.php

    Now it's working for me.

    P.s You have some great ideas for testing tools in Laravel, please keep them coming...

    Reviewed by mcampbell508 at 2016-04-02 11:12
  • 9. Laravel 8.x Compatibility

    This is an automated pull request from Shift to update your package code and dependencies to be compatible with Laravel 8.x.

    Before merging, you need to:

    • Checkout the l8-compatibility branch
    • Review all comments for additional changes
    • Thoroughly test your package

    If you do find an issue, please report it by commenting on this PR to help improve future automation.

    Reviewed by laravel-shift at 2020-09-08 02:46
  • 10. Convert relation column id to closure

    Instead of

    $factory->define(App\User::class, function (Faker\Generator $faker) {
        return [
            'company_id' => factory(App\Company::class)->create()->id,
        ];
    });
    

    it should be

    $factory->define(App\User::class, function (Faker\Generator $faker) {
        return [
            'company_id' => function() {
                  return factory(App\Company::class)->create();
             },
        ];
    });
    
    
    Reviewed by ajcastro at 2019-06-23 13:47
  • 11. Fix for getForeignKey() exception on Laravel > 5.8

    Fix for exception: Exception: Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::getForeignKey() on Laravel >= 5.8 while still maintaining backwards compatibility with Laravel < 5.8

    Reviewed by SvenSlijkoord at 2019-06-22 14:56
  • 12. Error when upgrading laravel 7 to laravel 8

    When upgrading from larvel 7 to laravel 8:

        - mpociot/laravel-test-factory-helper v2.1.0 requires illuminate/filesystem ^6.0|^7.0 -> satisfiable by illuminate/filesystem[v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev].
        - Only one of these can be installed: illuminate/filesystem[v5.5.0, ..., 5.8.x-dev, v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev], laravel/framework[v8.0.0, ..., 8.x-dev]. laravel/framework replaces illuminate/filesystem and thus cannot coexist with it.
    
    
    Reviewed by nezaboravi at 2021-02-05 11:13
  • 13. Does not work with Laravel 6.0 cannot install

    Conflicts with fakerphp/faker, because it requires higher version if I understand correctly. I do not want to do any workarounds, because later upgrading to new Laravel LTS version might cause more headache.

    After running:

    composer require mpociot/laravel-apidoc-generator
    

    This happens:

    ./composer.json has been updated
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
    Your requirements could not be resolved to an installable set of packages.
    
      Problem 1
        - Conclusion: remove laravel/framework v6.20.4
        - Conclusion: don't install laravel/framework v6.20.4
        - mpociot/laravel-apidoc-generator 2.1.8 requires laravel/framework ~5.4 -> satisfiable by laravel/framework[5.4.x-dev, 5.5.x-dev, 5.6.x-dev, 5.7.x-dev, 5.8.x-dev].
        - mpociot/laravel-apidoc-generator 2.x-dev requires laravel/framework ~5.4 -> satisfiable by laravel/framework[5.4.x-dev, 5.5.x-dev, 5.6.x-dev, 5.7.x-dev, 5.8.x-dev].
        - Can only install one of: laravel/framework[5.5.x-dev, v6.20.4].
        - Can only install one of: laravel/framework[5.6.x-dev, v6.20.4].
        - Can only install one of: laravel/framework[5.7.x-dev, v6.20.4].
        - Can only install one of: laravel/framework[5.8.x-dev, v6.20.4].
        - Can only install one of: laravel/framework[5.4.x-dev, v6.20.4].
        - Installation request for laravel/framework (locked at v6.20.4, required as ^6.20) -> satisfiable by laravel/framework[v6.20.4].
        - Installation request for mpociot/laravel-apidoc-generator ^2.1.8 -> satisfiable by mpociot/laravel-apidoc-generator[2.1.8, 2.x-dev].
    
    
    Installation failed, reverting ./composer.json to its original content.
    
    [email protected] MINGW64 ~/Desktop/lara-six/rest-pass
    $ composer require mpociot/laravel-apidoc-generator
    
    [email protected] MINGW64 ~/Desktop/lara-six/rest-pass
    $ composer require mpociot/laravel-apidoc-generator
    Using version ^4.8 for mpociot/laravel-apidoc-generator
    ./composer.json has been updated
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
    Your requirements could not be resolved to an installable set of packages.
    
      Problem 1
        - Conclusion: don't install mpociot/laravel-apidoc-generator 4.8.2
        - Conclusion: don't install mpociot/laravel-apidoc-generator 4.8.1
        - Conclusion: don't install mpociot/laravel-apidoc-generator 4.8.0
        - Conclusion: remove fakerphp/faker v1.11.0
        - Installation request for mpociot/laravel-apidoc-generator ^4.8 -> satisfiable by mpociot/laravel-apidoc-generator[4.8.0, 4.8.1, 4.8.2, v4.x-dev].
        - Conclusion: don't install fakerphp/faker v1.11.0
        - mpociot/laravel-apidoc-generator v4.x-dev requires fzaninotto/faker ^1.8 -> satisfiable by fakerphp/faker[1.9.x-dev, v1.9.1], fzaninotto/faker[1.9.x-dev, v1.8.0, v1.9.0, v1.9.1].
        - Can only install one of: fakerphp/faker[1.9.x-dev, v1.11.0].
        - Can only install one of: fakerphp/faker[v1.9.1, v1.11.0].
        - fzaninotto/faker 1.9.x-dev conflicts with fakerphp/faker[v1.11.0].
        - fzaninotto/faker v1.8.0 conflicts with fakerphp/faker[v1.11.0].
        - fzaninotto/faker v1.9.0 conflicts with fakerphp/faker[v1.11.0].
        - fzaninotto/faker v1.9.1 conflicts with fakerphp/faker[v1.11.0].
        - Installation request for fakerphp/faker (locked at v1.11.0, required as ^1.9.1) -> satisfiable by fakerphp/faker[v1.11.0].
    
    
    Installation failed, reverting ./composer.json to its original content.
    
    Reviewed by rokaspaulik at 2020-11-18 15:56
  • 14. Better support for enums.

    Fix proposed in #51 for issue #50 will remove SQL error, but also make enum fields always a $faker->word in generated factories. PostgreSQL implementation of enum does not store allowed values in type definition, instead there is a field constraint.

    I came up with solution that supports both MySQL and PostgreSQL. Right now it should work even without a custom enum type for Doctrine.

    I tested it with PostgreSQL and this migration:

    Schema::create('tests', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->enum('test', ['one', 'two', 'three']);
        $table->timestamps();
    });            
    

    Generated factory:

    $factory->define(App\Models\Test::class, function (Faker $faker) {
        return [
            'test' => $faker->randomElement(['one', 'two', 'three']),
        ];
    });
    

    Changes that were made:

    • Model object is passed all the way to enumValues function to check connection driver name.
    • Function enumValues is not static anymore (I honestly don't know why it was).
    • Enum values parsing from field constraint for PostgreSQL has been implemented based on this question on StackOverflow.
    • Field mapped in setProperty is returned instantly if matches any of $fakeableNames, so it won't make a DB call for enum.
    • Field is set to enum with $faker->randomElement if any enum values are present (only if it's an actual enum field in database).
    Reviewed by TheDoctor0 at 2020-06-27 11:25
Ray server is a beautiful, lightweight php app build on Laravel that helps you debug your app. It runs without installation on multiple platforms.
Ray server is a beautiful, lightweight php app build on Laravel that helps you debug your app. It runs without installation on multiple platforms.

RayServer is a beautiful, lightweight web server built on Laravel and VueJs that helps debugging your app. It runs without installation on multiple platforms.

May 16, 2022
Buggregator is a beautiful, lightweight web server built on Laravel and VueJs that helps debugging your app.
Buggregator is a beautiful, lightweight web server built on Laravel and VueJs that helps debugging your app.

A server for debugging more than just Laravel applications. Buggregator is a beautiful, lightweight web server built on Laravel and VueJs that helps d

May 16, 2022
Php Debugger to run in terminal to debug your code easily.
Php Debugger to run in terminal to debug your code easily.

What is Dephpugger? Dephpugger (read depugger) is an open source lib to make a debug in php direct in terminal, without necessary configure an IDE. Th

Jan 12, 2022
Clockwork - php dev tools in your browser - server-side component
Clockwork - php dev tools in your browser - server-side component

Clockwork is a development tool for PHP available right in your browser. Clockwork gives you an insight into your application runtime - including requ

May 18, 2022
An artisan command to tail your application logs
An artisan command to tail your application logs

Easily tail your logs This package offers an artisan command to tail the application log. It supports daily and single logs on your local machine. To

May 10, 2022
Php Debugger to run in terminal to debug your code easily.
Php Debugger to run in terminal to debug your code easily.

What is Dephpugger? Dephpugger (read depugger) is an open source library that allows a developer to debug in php direct in terminal, without necessary

May 20, 2022
A simple Craft module, inspired by Mildly Geeky's "Kint", to debug Twig within your browser
A simple Craft module, inspired by Mildly Geeky's

A simple Craft module, inspired by Mildly Geeky's "Kint", to debug Twig within your browser

Feb 2, 2022
Laravel Dumper - Improve the default output of dump() and dd() in Laravel projects

Laravel Dumper Improve the default output of dump() and dd() in Laravel projects. Improves the default dump behavior for many core Laravel objects, in

May 12, 2022
Laravel Debugbar (Integrates PHP Debug Bar)
Laravel Debugbar (Integrates PHP Debug Bar)

Laravel Debugbar This is a package to integrate PHP Debug Bar with Laravel. It includes a ServiceProvider to register the debugbar and attach it to th

May 24, 2022
A beautiful error page for Laravel apps
A beautiful error page for Laravel apps

Ignition: a beautiful error page for Laravel apps Ignition is a beautiful and customizable error page for Laravel applications running on Laravel 5.5

May 13, 2022
:dromedary_camel: Laravel log viewer
:dromedary_camel: Laravel log viewer

Laravel log viewer TL;DR Log Viewer for Laravel 5, 6, 7 & 8 (still compatible with 4.2 too) and Lumen. Install with composer, create a route to LogVie

May 24, 2022
:page_with_curl: Provides a log viewer for Laravel
:page_with_curl: Provides a log viewer for Laravel

LogViewer By ARCANEDEV© This package allows you to manage and keep track of each one of your log files. NOTE: You can also use LogViewer as an API. Of

May 13, 2022
A Laravel Package to integrate Nette Tracy Debugger
A Laravel Package to integrate Nette Tracy Debugger

Nette Tracy for Laravel 5 Better Laravel Exception Handler Features Visualization of errors and exceptions Debugger Bar (ajax support @v1.5.6) Excepti

May 3, 2022
An elegant debug assistant for the Laravel framework.
An elegant debug assistant for the Laravel framework.

Introduction Laravel Telescope is an elegant debug assistant for the Laravel framework. Telescope provides insight into the requests coming into your

May 19, 2022
This package connects a Laravel Octance application with Tideways for PHP Monitoring, Profiling and Exception Tracking.

Tideways Middleware for Laravel Octane This package connects a Laravel Octance application with Tideways for PHP Monitoring, Profiling and Exception T

Jan 6, 2022
🏭 An easy way to generate populated factories for models.
🏭 An easy way to generate populated factories for models.

Laravel Populated Factory provides an easy way to generate populated factories for models according to types & names of their columns. Install You can

May 12, 2022
Laravel Migrations Generator: Automatically generate your migrations from an existing database schema.

Laravel Migrations Generator Generate Laravel Migrations from an existing database, including indexes and foreign keys! Upgrading to Laravel 5.4 Pleas

May 15, 2022
May 8, 2022
Laravel Migrations Generator: Automatically generate your migrations from an existing database schema.

Laravel Migrations Generator Generate Laravel Migrations from an existing database, including indexes and foreign keys! This package is cloned from ht

May 21, 2022
Generate trends for your models. Easily generate charts or reports.
Generate trends for your models. Easily generate charts or reports.

Laravel Trend Generate trends for your models. Easily generate charts or reports. Support us Like our work? You can support us by purchasing one of ou

May 22, 2022