Guess attributes for Laravel model factories

Overview

Eloquent Populator

This package provides default attributes for Laravel model factories by guessing the best Faker formatters from columns' names and types. For example, if a column is called first_name, it will use $faker->firstName(). If unable to guess by the column's name, it will guess the formatter by the column's type; for example, it will use $faker->text() for a VARCHAR column, or a Carbon instance for a TIMESTAMP. Models of BelongsTo relationships that have been defined are created as well. Furthermore, if you use the Multilingual package, for translatable attributes Populator will generate arrays with a different value for each configured locale.

Compared to packages that generate factories once, you generally don't have to update your factories as you change their table definitions and they will be very small.

Due to the improvements in Laravel 8's model factories, in version 3 Populator has been rewritten to integrate with them instead of wrapping them. As a result, the convenient syntax to seed the database with bulk inserts while connecting all relationships has been lost, but you no longer have to deviate from Laravel's API and the complexity of the package has been drastically reduced.

Installation

Install the package with Composer:

composer require --dev guidocella/eloquent-populator

Model factory integration

Call Populator::guessFormatters($this->model) in your factories' definition methods to get an array with the guessed formatters. You may merge these with custom attributes whose guessed formatter isn't accurate.

use GuidoCella\EloquentPopulator\Populator;

...

public function definition()
{
    return array_merge(Populator::guessFormatters($this->model), [
            'avatar' => $this->faker->imageUrl()
    ]);
}

If you execute php artisan stub:publish, you can include the call to Populator in factory.stub so that php artisan make:factory will add it.

After guessing a model's formatters once, they are cached in a static property even across different tests.

Seeding

Before seeding your database you'll want to call setSeeding().

public function run()
{
    Populator::setSeeding();

Its effect is that nullable columns will have a 50% chance of being set to null or to the guessed formatter.

Testing

If setSeeding() wasn't called nullable columns will always be set to their guessed formatter. The idea is to simplify tests such as this:

public function testSubmitWithoutName() {
    $user = User::factory()->make(['name' => null]);
    // test that submitting a form with $user's attributes causes an error
}

public function testSubmitWithCorrectName() {
    $user = User::factory()->make();
    // no need to specify the correct formatter for name since it can't be null
    // test that submitting a form with $user's attributes is succesful
}

On the other hand, seeding the database with null attributes lets you notice Trying to get property of non-object errors.

You might also like...
Generate previous attributes when saving Eloquent models
Generate previous attributes when saving Eloquent models

This package provides a trait that will generate previous attributes when saving any Eloquent model.

This package allows you to render livewire components like a blade component, giving it attributes, slots etc

X-livewire This package allows you to render livewire components like a blade component, giving it attributes, slots etc. Assuming you wanted to creat

A simple pure PHP RADIUS client supporting Standard and Vendor-Specific Attributes in single file

BlockBox-Radius A simple pure PHP RADIUS client supporting Standard and Vendor-Specific Attributes in single file Author: Daren Yeh [email protected]

A Laravel package that adds a simple image functionality to any Laravel model
A Laravel package that adds a simple image functionality to any Laravel model

Laraimage A Laravel package that adds a simple image functionality to any Laravel model Introduction Laraimage served four use cases when using images

Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

This Laravel package merges staudenmeir/eloquent-param-limit-fix and staudenmeir/laravel-adjacency-list to allow them being used in the same model.

This Laravel package merges staudenmeir/eloquent-param-limit-fix and staudenmeir/laravel-adjacency-list to allow them being used in the same model.

Easily create a revision history for any laravel model
Easily create a revision history for any laravel model

Wouldn't it be nice to have a revision history for any model in your project, without having to do any work for it. By simply adding the RevisionableT

laravel-model-validator

laravel-model-validator This is a simple validator. The validator can be created by command. The validator has all common table column constraint, eg:

Automatic Laravel model migrations.

Laravel Automatic Migrations Automatic Laravel model migrations. Instead of having to create and manage migration files, this package allows you to sp

Comments
  • Question: Relation between three models, sharing same

    Question: Relation between three models, sharing same "owner_id"?

    Hi, not sure how to call it, but in essence I have a category and item - and user who created both of them. So Item belongsTo one creator_id, and category as well belongsTo one creator_id. Item can have one category (doesn't have to), but if it does then both creator_ids needs to be the same for both item and category. Meaning, one user created both category and item that belongs to the category (hope that makes sense).

    Is there any easy way of doing this with populator, or would I need to manually relate them during/after the seeding?

    Thanks!

    opened by dakipro 6
  • Custom User model?

    Custom User model?

    How i use custom User model?

    For example

    my user migration,

    Schema::create('users', function (Blueprint $table) {
                $table->increments('id')->unique();
                $table->string('username');
                $table->timestamps();
            });
    
    

    and user model is

    protected $table= 'users';
    
        function posts(){
            return $this->hasMany('App\Post');
        }
        function comments(){
            return $this->hasMany('App\Comment');
        }
    

    and when i tried $populator->add(User::class,10)->seed(); , i see SQLSTATE[42S22]: Column not found: 1054 Unknown column 'email' in 'field list' (SQL: insert into users (created_at, email, email_verified_at, name, `p

    Please help.

    opened by ozgurkaracam 1
  • README has a typo in an example causing

    README has a typo in an example causing "Call to undefined method"

    $populator->add(User::class)->attachQuantites([Role::class => 5, Club::class => 0]);
    

    specifically attachQuantites should be attachQuantities (last i is missing).

    A typo is no big deal, of course, but it can be frustrating when copy-pasting examples.

    PS: Thank you for the great library!

    opened by atanas-dev 1
Releases(v3.0.2)
Owner
Guido Cella
Guido Cella
Make your own custom cast type for Laravel model attributes

Laravel Custom Casts Make your own cast type for Laravel model attributes Laravel custom casts works similarly to Eloquent attribute casting, but with

Vladimir Ković 220 Oct 28, 2022
Cast your Eloquent model attributes to Value Objects with ease.

Laravel Value Objects Cast your Eloquent model attributes to value objects with ease! Requirements This package requires PHP >= 5.4. Using the latest

Red Crystal Code 23 Dec 30, 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
A laravel package to handle sanitize process of model data to create/update model records.

Laravel Model UUID A simple package to sanitize model data to create/update table records. Installation Require the package using composer: composer r

null 66 Sep 19, 2022
A laravel package to generate model hashid based on model id column.

Laravel Model Hashid A package to generate model hash id from the model auto increment id for laravel models Installation Require the package using co

Touhidur Rahman 13 Jan 20, 2022
A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

Touhidur Rahman 17 Jan 20, 2022
🔌 Autowire and configure using PHP 8 Attributes in Laravel.

?? Autowire for Laravel Autowire and configure using PHP 8 Attributes in Laravel. Installation Via Composer composer require jeroen-g/autowire You wil

JeroenG 13 Oct 7, 2022
Provide all attributes (including irregular patterns) to Laravel Blade class components.

blade-wants-attributes blade-wants-attributes offers you the ability to use Blade/HTML-defined attributes within the constructors of Laravel Blade cla

Stephan Casas 4 Sep 15, 2022
Control frontend access to properties/methods in Livewire using PHP 8 attributes.

This package adds PHP 8.0 attribute support to Livewire. In specific, the attributes are used for flagging component properties and methods as frontend-accessible.

ARCHTECH 83 Dec 17, 2022
Easily validate data attributes through a remote request

Laravel Remote Rule Easily validate data attributes through a remote request. This package allows you to define a subset of custom rules to validate a

H-FARM Innovation 27 Nov 20, 2022