PHP code example of thettler / laravel-factory-classes

1. Go to this page and download the library: Download thettler/laravel-factory-classes library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

thettler / laravel-factory-classes example snippets


$concert = factory(Concert::class)->create([
    'date' => now()
]);
$venue = factory(Venue::class)->create();
$headliner = factory(Artist::class)->create();
$support = factory(Artist::class)->create();

$concert->venue()->associate($venue);
$concert->lineup()->attach($headliner->id, ['headliner'=> true]);
$concert->lineup()->attach($support->id, ['headliner'=> false]);

$this->assert($concert, /*Do something with your Concert*/);

$concert = ConcertFatory::new()
            ->date(now())
            ->withVenue()
            ->withHeadliner()
            ->withSupport()
            ->create();

$this->assert($concert, /*Do something with your Concert*/);



namespace App\Factories;

use App\Concert;
use Faker\Generator;
use Illuminate\Support\Carbon;
use Thettler\LaravelFactoryClasses\FactoryClass;

class ConcertFactory extends FactoryClass
{
    protected string $model = Concert::class;

    protected function fakeData(Generator $faker): array
    {
        return [
            'date' => $faker->dateTimeBetween('-5 years', '+5 years'),
            /* More attributes*/
        ];
    }

    public function create(array $extra = []): Concert
    {
        return $this->createModel($extra);
    }

    public function make(array $extra = []): Concert
    {
       return $this->makeModel($extra);
    }

    public function date(Carbon $data): self
    {
        return $this->addData('date', $data);
    }

    public function withVenue($venueFactory = null): self
    {
        return $this->belongsTo('venue', $venueFactory ?? VenueFactory::new());
    }

    public function withHeadliner(...$artistFactories): self
    {
        return $this->belongsToMany(
            'lineups',
            empty($artistFactories) ? [ArtistFactory::new()] : $artistFactories,
            fn(BelongsToManyFactoryRelation $relation) => $relation->pivot(['headliner' => true])
        );
    }

    public function withSupport(...$artistFactories): self
    {
        return $this->belongsToMany(
            'lineups',
            empty($artistFactories) ? [ArtistFactory::new()] : $artistFactories,
            fn(BelongsToManyFactoryRelation $relation) => $relation->pivot(['headliner' => true])
        );
    }

}




/*
 * You can place your custom package configuration in here.
 */
return [
    'models_path' => base_path('app'),

    'factories_path' => base_path('app/Factories'),

    'factories_namespace' => 'App\Factories',
];


namespace App\Factories;

use Thettler\LaravelFactoryClasses\FactoryClass;
use App\User;

class UserFactory extends FactoryClass {
      protected string $model = User::class;
}


namespace App\Factories;

use Thettler\LaravelFactoryClasses\FactoryClass;

class UserFactory extends FactoryClass {
      /*...*/

     public function create(array $extra = []): User
      {
          return $this->createModel($extra);
      }
}


namespace App\Factories;

use Thettler\LaravelFactoryClasses\FactoryClass;

class UserFactory extends FactoryClass {
      /*...*/

     public function make(array $extra = []): User
      {
          return $this->makeModel($extra);
      }
}


namespace App\Factories;

use Thettler\LaravelFactoryClasses\FactoryClass;

class UserFactory extends FactoryClass {
      /*...*/

    protected function fakeData(\Faker\Generator $faker): array
    {
        return [
            'name' => $faker->name,
            'email' => $faker->unique()->safeEmail,
            'email_verified_at' => now(),
            'password' => Hash::make('secret'),
            'remember_token' => Str::random(10),
        ];
    }
}


namespace App\Factories;

use Thettler\LaravelFactoryClasses\FactoryClass;
use App\User;

class UserFactory extends FactoryClass {

        protected string $model = User::class;

        public function create(array $extra = []): User
        {
            return $this->createModel($extra);
        }

        public function make(array $extra = []): User
        {
            return $this->makeModel($extra);
        }

        protected function fakeData(\Faker\Generator $faker): array
        {
            return [
                'name' => $faker->name,
                'email' => $faker->unique()->safeEmail,
                'email_verified_at' => now(),
                'password' => Hash::make('secret'),
                'remember_token' => Str::random(10),
            ];
        }
}

$userFactory = UserFactory::new();

$userFactory = UserFactory::new();
$userModel = $userFactory->create();

$userFactory = UserFactory::new();
$userModel = $userFactory->make();

$threeSavedUserCollection = UserFactory::new()->createMany(3);
$threeNotSavedUserCollection = UserFactory::new()->makeMany(3);

$user = UserFactory::new()
            ->addData('name', 'myName')
            ->create();

echo $user->name; // myName
 

 $user = UserFactory::new()
            ->data(['name' => 'myName'])
            ->create();
 echo $user->name; // myName

$user = UserFactory::new()->create(['name' => 'extraName']);
echo $user->name; // extraName

$user = UserFactory::new()->make(['name' => 'extraName']);
echo $user->name; // extraName

$userCollection = UserFactory::new()->createMany(2, ['name' => 'extraName']);
$userCollection->pluck('name')->all(); // ['extraName', 'extraName']

$user = UserFactory::new()->makeMany(2, ['name' => 'extraName']);
$userCollection->pluck('name')->all(); // ['extraName', 'extraName']

$userCollection = UserFactory::new()->createMany(2, [['name' => 'firstName'], ['name' => 'secondName']]);
$userCollection->pluck('name')->all(); // ['firstName', 'secondName']

$userCollection = UserFactory::new()->createMany(3, [['name' => 'firstName'], ['name' => 'secondName']]);
$userCollection->pluck('name')->all(); // ['firstName', 'secondName', '<value-from-fakeData>']

use Thettler\LaravelFactoryClasses\FactoryClass;

class UserFactory extends FactoryClass {
      /*...*/

    public function name(string $name): self
    {
        return $this->addData('name', $name);
    }
}

 $user = UserFactory::new()
            ->name('myName')
            ->create();
 echo $user->name; // myName

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

$user = UserFactory::new()->hasOne('company', CompanyFactory::new())->create();
$user->company; // Some new created Company
// Or
$company = Company::find('xy');
$user = UserFactory::new()->hasOne('company', $company)->create();
$user->company; // Company XY

class User extends Model {
    public function companies(): HasMany {
        return $this->hasMany(Company::class);
    }
}

$user = UserFactory::new()->belongsTo('companies',[CompanyFactory::new()])->create();
$user->companies[0]; // Some new created Company
// Or
$company = Company::find('xy');
$user = UserFactory::new()->belongsTo('companies', [$company])->create();
$user->companies[0]; // Company XY

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

$user = UserFactory::new()->belongsTo('company', CompanyFactory::new())->create();
$user->company; // Some new created Company
// Or
$company = Company::find('xy');
$user = UserFactory::new()->belongsTo('company', $company)->create();
$user->company; // Company XY

class User extends Model {
    public function companies(): BelongsToMany {
        return $this->belongsToMany(Company::class);
    }
}

$user = UserFactory::new()->belongsToMany('companies', CompanyFactory::new())->create();
$user->companies[0]; // Some new created Company
// Or
$company = Company::find('xy');
$user = UserFactory::new()->belongsToMany('companies', $company)->create();
$user->companies[0]; // Company XY

class User extends Model {
    public function companies(): BelongsToMany {
        return $this->belongsToMany(Company::class)->withPivot('role');
    }
}

$user = UserFactory::new()
         ->belongsToMany(
            'companies', 
            CompanyFactory::new(),
            fn(BelongsToManyFactoryRelation $relation) => $relation->pivot(['role' => 'manager'])
         )
         ->create();
$user->companies[0]->role; // manager

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

$user = UserFactory::new()->morphTo('company', CompanyFactory::new())->create();
$user->company; // Some new created Company
// Or
$company = Company::find('xy');
$user = UserFactory::new()->morphTo('company', $company)->create();
$user->company; // Company XY

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

$user = UserFactory::new()->morphOne('company', CompanyFactory::new())->create();
$user->company; // Some new created Company
// Or
$company = Company::find('xy');
$user = UserFactory::new()->morphOne('company', $company)->create();
$user->company; // Company XY

use Thettler\LaravelFactoryClasses\FactoryClass;

class UserFactory extends FactoryClass {
      /*...*/

    public function withCompany($company = null): self
    {
        return $this->belongsTo('company', $company ?? CompanyFactory::new());
    }
}

 $user = UserFactory::new()
            ->withCompany()
            ->create();
 echo $user->company; // Company XY

use Thettler\LaravelFactoryClasses\FactoryClass;

class UserFactory extends FactoryClass {
      /*...*/

    public function withCompanies(...$companies): self
    {
        return $this->belongsToMany('companies', empty($companies) ? [CompanyFactory::new()] : $companies);
    }
}

 $user = UserFactory::new()
            ->withCompanies()
            ->create();
 echo $user->companies[0]; // Company

class User extends Model {
    // Would generate a withCompany() method on your factory
    public function company(): BelongsTo {
        return $this->belongsto(Company::class);
    }
    // Would not generate a withCompany() method on your factory
    public function company() {
        return $this->belongsto(Company::class);
    }
}

 $user = UserFactory::new()
            ->withoutFakeData()
            ->make();

use Thettler\LaravelFactoryClasses\FactoryClass;
use App\User;

class UserFactory extends FactoryClass {

         /* ... */

        public function withCompany ($company) {
            return $this->belongsTo(
                'company', 
                $company, 
                fn(\Thettler\LaravelFactoryClasses\Relations\BelongsToFactoryRelation $relation) => $relation
                ->type('before') // after|before this indicates if the relation creation should take place before or after the main Model has ben created and saved to the DB
                ->relation('diffrentCompany') // change the name of the relation that gets used so here it changes from 'company' to 'differentCompany'
                ->factories(CompanyFactory::new()->withSpecialState()) // Lets you add an one or more Factories to the Relation !! only the many relations using mor then one factory
                ->models(Company::find('xy')) // Same as factories() only for Models 
            );
        }
}

use Thettler\LaravelFactoryClasses\FactoryClass;
use App\User;

class UserFactory extends FactoryClass {

         /* ... */

        public function withCompany ($company) {
            return $this->with(MyFactoryRelation::new('company', $company));
        }
}

namespace Thettler\LaravelFactoryClasses\Relations;

use Illuminate\Database\Eloquent\Model;
use Thettler\LaravelFactoryClasses\FactoryRelation;

class BelongsToFactoryRelation extends FactoryRelation
{
    protected string $type = self::BEFORE_TYPE; // after|before this indicates if the relation creation should take place before or after the main Model has ben created and saved to the DB

    /**
    * This Method will be used if the make() or makeMany() method gets used it gets the current Model (in our case User) and returns this Model again
    * 
    * @param Model $model
    * @return Model
    * @throws \Thettler\LaravelFactoryClasses\Exceptions\FactoryException
    */
    public function make(Model $model): Model
    {
        $relative = $this->convertRelative($this->relatives[0], 'make');
        return $model->setRelation($this->relation, $relative);
    }

    /**
    * This Method will be used if the create() or createMany() method gets used it gets the current Model (in our case User) and returns this Model again
    * 
    * @param Model $model
    * @return Model
    * @throws \Thettler\LaravelFactoryClasses\Exceptions\FactoryException
    */
    public function create(Model $model): Model
    {
        $relation = $this->relation;
        $relative = $this->convertRelative($this->relatives[0]);
        $model->$relation()->associate($relative)->save();
        return $model;
    }
}

bash
php artisan vendor:publish --provider="Thettler\LaravelFactoryClasses\FactoryClassServiceProvider"
bash
php artisan make:factory-class
bash
php artisan make:factory-class User
bash
php artisan make:factory-class User --force
bash
php artisan make:factory-class User --recursive