master

laravel/framework

Last updated at: 29/12/2023 09:22

HasFactory.php

TLDR

The HasFactory.php file is a trait in the Illuminate\Database\Eloquent\Factories namespace. It provides two methods for the models that use it: factory() and newFactory(). The factory() method returns a new factory instance for the model, allowing the creation of model instances with predefined attributes and states. The newFactory() method is a placeholder method that can be overridden in the model classes to customize the factory creation process.

Methods

factory()

The factory($count = null, $state = []) method is used to create a new factory instance for the model. It accepts two optional parameters: $count and $state.

  • $count: It can be set to a numeric value to specify the number of model instances to be created. If not provided, the default value is null.
  • $state: It can be set to a callable or an array to define additional states for the created model instances. If not provided, the default value is an empty array [].

This method internally calls the newFactory() method to get the factory instance and then applies the desired count and state configurations. Finally, it returns the configured factory instance.

newFactory()

The newFactory() method is a protected method that can be overridden in model classes to customize the creation of factory instances. By default, this method is empty (// denotes an empty method in the code). If the method is not overridden, the factory() method will use the Factory::factoryForModel(get_called_class()) method to get the factory instance for the model.

END

<?php

namespace Illuminate\Database\Eloquent\Factories;

trait HasFactory
{
    /**
     * Get a new factory instance for the model.
     *
     * @param  callable|array|int|null  $count
     * @param  callable|array  $state
     * @return \Illuminate\Database\Eloquent\Factories\Factory<static>
     */
    public static function factory($count = null, $state = [])
    {
        $factory = static::newFactory() ?: Factory::factoryForModel(get_called_class());

        return $factory
                    ->count(is_numeric($count) ? $count : null)
                    ->state(is_callable($count) || is_array($count) ? $count : $state);
    }

    /**
     * Create a new factory instance for the model.
     *
     * @return \Illuminate\Database\Eloquent\Factories\Factory<static>
     */
    protected static function newFactory()
    {
        //
    }
}