Generate Laravel test factories from your existing models

Overview

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.

Comments
  • Installation fails with an error

    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
    
    opened by nunomira 12
  • Allow override relations columns

    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;
            }
    
    opened by markinigor 6
  • Better support for enums.

    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).
    opened by TheDoctor0 5
  • Allow

    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']),
    ...
    
    opened by skeets23 5
  • Not Support in laravel 5.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

    opened by ghost 4
  • Not working on laravel 5.3

    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

    opened by dieg0 4
  • Update and streamline package for common use case

    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.

    opened by jasonmccreary 2
  • Non-functioning in Laravel 5.5

    Non-functioning in Laravel 5.5

    opened by AlbinoDrought 2
  • Use PSR-4 autoloading

    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...

    opened by mcampbell508 2
  • Laravel 8.x Compatibility

    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.

    opened by laravel-shift 1
  • Convert relation column id to closure

    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();
             },
        ];
    });
    
    
    opened by ajcastro 1
  • Support for laravel 8

    Support for laravel 8

    This PR updates the blade template used by the factory to a Laravel 8 version, and changes the default model source to app/Models

    I haven't added a configuration option for switching between Laravel versions, so this branch will only work with Laravel 8 and similar versions.

    This hasn't been tested with Laravel 9.

    opened by rickgladwin 0
  • Error when upgrading laravel 7 to laravel 8

    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.
    
    
    opened by nezaboravi 2
  • Does not work with Laravel 6.0 cannot install

    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.
    
    Rokas@DESKTOP MINGW64 ~/Desktop/lara-six/rest-pass
    $ composer require mpociot/laravel-apidoc-generator
    
    Rokas@DESKTOP 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.
    
    opened by rokaspaulik 0
Releases(v2.1.0)
Owner
Marcel Pociot
Marcel Pociot
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.

Pavel Buchnev 310 Jan 2, 2023
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

Buggregator 311 Jan 4, 2023
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

Renato Cassino 190 Dec 3, 2022
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

its 4.8k Dec 29, 2022
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

Spatie 677 Dec 29, 2022
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

Renato Cassino 190 Dec 3, 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 "Kint", to debug Twig within your browser

TrendyMinds 4 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

Galahad 301 Dec 26, 2022
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

Barry vd. Heuvel 14.8k Jan 9, 2023
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

Facade 2k Jan 1, 2023
: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

Raphaël Huchet 2.9k Jan 5, 2023
: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

ARCANEDEV 2.3k Dec 30, 2022
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

Recca Tsai 383 Dec 6, 2022
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

The Laravel Framework 4.4k Dec 27, 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

Tideways 7 Jan 6, 2022
QaraTMS is open source test case, test suites, test plans and test runs management tool.

QaraTMS - Open Source Test Management System QaraTMS is open source test management software for managing test suites, test cases, test plans, test ru

Alex H 29 Dec 22, 2022
🏭 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

Coderello 241 Nov 25, 2022
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

Flowframe 139 Dec 27, 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

Bernhard Breytenbach 3.3k Dec 30, 2022
Ariama Victor (A.K.A. OVAC4U) 106 Dec 25, 2022