Skip to content
No description, website, or topics provided.
PHP
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
docs
src
tests
.gitignore
LICENSE.md
README.md
composer.json

README.md

Model state factory methods

Latest Version on Packagist Software License Total Downloads

Installation

You can install the package via composer:

composer require bjornvoesten/laravel-model-state-factory-methods

Usage

Defining models

Create an Eloquent model and define the states that should be available.

Available states can be defined by using an array with attributes and values.

class User extends Model 
{
    /**
     * The model states.
     *
     * @return array
     */
    public $states = [
        'activated' => [
            'activated' => true,
        ],
        ...
    ];
}

Or define the available states using an array with state classes. The state names are automatically guessed by taking the state class name. The name for example the class ActivatedState will become activated.

class User extends Model 
{
    /**
     * The model states.
     *
     * @return array
     */
    public $states = [
        'App\States\ActivatedState',
        'App\States\DeletedState',
    ];
}

Or give the state a custom name.

class User extends Model 
{
    /**
     * The model states.
     *
     * @return array
     */
    public $states = [
        'activated' => 'App\States\ActivatedState',
        'deleted' => 'App\States\DeletedState',
        ...
    ];
}

Defining states

The state class has to have the attributes method which returns the array with attributes and values.

class ActivatedState
{
    /**
     * The state's attributes.
     * 
     * @param \Illuminate\Database\Eloquent\Model $model
     * @return array
     */
    public function attributes($model)
    {
        return [
            'activated' => true,
        ];
    }
}

Creating models

Creating a model with applied states can be done by calling the state or states method on the model or Eloquent builder.

Create a model with a single state:

\App\User::state('active')->create([
    'email' => 'example@example.com',
));

Or with multiple states:

\App\User::states('active', 'deleted')->create([
    'email' => 'example@example.com',
));

Or provide multiple states in an array:

\App\User::states(['active', 'deleted'])->create([
    'email' => 'example@example.com',
));

Available factory methods

  • make
  • create
  • firstOrNew
  • firstOrCreate

Testing

$ composer test

License

The MIT License (MIT). Please see License File for more information.

You can’t perform that action at this time.