All Projects → spatie → Laravel Model Status

spatie / Laravel Model Status

Licence: mit
Easily add statuses to your models

Projects that are alternatives of or similar to Laravel Model Status

Befriended
Eloquent Befriended brings social media-like features like following, blocking and filtering content based on following or blocked models.
Stars: ✭ 596 (+16.86%)
Mutual labels:  eloquent, laravel, model
Elasticsearch
The missing elasticsearch ORM for Laravel, Lumen and Native php applications
Stars: ✭ 375 (-26.47%)
Mutual labels:  eloquent, laravel, model
Plans
Laravel Plans is a package for SaaS apps that need management over plans, features, subscriptions, events for plans or limited, countable features.
Stars: ✭ 326 (-36.08%)
Mutual labels:  eloquent, laravel, model
Laravel Sluggable
An opinionated package to create slugs for Eloquent models
Stars: ✭ 831 (+62.94%)
Mutual labels:  eloquent, laravel, model
Guardian
Eloquent Guardian is a simple permissions system for your users. While there are many other packages for permissions, this one solves everything in the most eloquent way.
Stars: ✭ 121 (-76.27%)
Mutual labels:  eloquent, laravel, model
Schedule
Schedule is a package that helps tracking schedules for your models. If you have workers in a company, you can set schedules for them and see their availability though the time.
Stars: ✭ 155 (-69.61%)
Mutual labels:  eloquent, laravel, model
Eager Load Pivot Relations
Eager load pivot relations for Laravel Eloquent's BelongsToMany relation.
Stars: ✭ 134 (-73.73%)
Mutual labels:  eloquent, laravel, model
Rating
Laravel Eloquent Rating allows you to assign ratings to any model.
Stars: ✭ 175 (-65.69%)
Mutual labels:  eloquent, laravel, model
Laravel Translator
An Eloquent translator for Laravel
Stars: ✭ 275 (-46.08%)
Mutual labels:  eloquent, laravel
Decoy
A Laravel model-based CMS
Stars: ✭ 303 (-40.59%)
Mutual labels:  eloquent, laravel
Laravel Bookings
Rinvex Bookable is a generic resource booking system for Laravel, with the required tools to run your SAAS like services efficiently. It's simple architecture, accompanied by powerful underlying to afford solid platform for your business.
Stars: ✭ 309 (-39.41%)
Mutual labels:  eloquent, laravel
Laravel Eloquent Join
This package introduces the join magic for eloquent models and relations.
Stars: ✭ 270 (-47.06%)
Mutual labels:  eloquent, laravel
Eloquent Builder
Provides an advanced filter for Laravel or Lumen model.
Stars: ✭ 264 (-48.24%)
Mutual labels:  eloquent, laravel
Laravel Attributes
Rinvex Attributable is a robust, intelligent, and integrated Entity-Attribute-Value model (EAV) implementation for Laravel Eloquent, with powerful underlying for managing entity attributes implicitly as relations with ease. It utilizes the power of Laravel Eloquent, with smooth and seamless integration.
Stars: ✭ 304 (-40.39%)
Mutual labels:  eloquent, laravel
Quicksand
Easily schedule regular cleanup of old soft-deleted Eloquent data.
Stars: ✭ 259 (-49.22%)
Mutual labels:  eloquent, laravel
laravel-boolean-dates
Automatically convert Eloquent model boolean attributes to dates (and back).
Stars: ✭ 31 (-93.92%)
Mutual labels:  eloquent, model
Corcel
Use WordPress backend with Laravel or any PHP application
Stars: ✭ 3,504 (+587.06%)
Mutual labels:  eloquent, laravel
Squire
A library of static Eloquent models for common fixture data.
Stars: ✭ 496 (-2.75%)
Mutual labels:  eloquent, laravel
Laravel Wallet
Easy work with virtual wallet
Stars: ✭ 401 (-21.37%)
Mutual labels:  eloquent, laravel
Laravel Model Cleanup
Clean up unneeded records
Stars: ✭ 388 (-23.92%)
Mutual labels:  eloquent, laravel

Assign statuses to Eloquent models

Latest Version on Packagist GitHub Workflow Status Check & fix styling Total Downloads

Imagine you want to have an Eloquent model hold a status. It's easily solved by just adding a status field to that model and be done with it. But in case you need a history of status changes or need to store some extra info on why a status changed, just adding a single field won't cut it.

This package provides a HasStatuses trait that, once installed on a model, allows you to do things like this:

// set a status
$model->setStatus('pending', 'needs verification');

// set another status
$model->setStatus('accepted');

// specify a reason
$model->setStatus('rejected', 'My rejection reason');

// get the current status
$model->status(); // returns an instance of \Spatie\ModelStatus\Status

// get the previous status
$latestPendingStatus = $model->latestStatus('pending');

$latestPendingStatus->reason; // returns 'needs verification'

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-model-status

You must publish the migration with:

php artisan vendor:publish --provider="Spatie\ModelStatus\ModelStatusServiceProvider" --tag="migrations"

Migrate the statuses table:

php artisan migrate

Optionally you can publish the config-file with:

php artisan vendor:publish --provider="Spatie\ModelStatus\ModelStatusServiceProvider" --tag="config"

This is the contents of the file which will be published at config/models-status.php

return [

    /*
     * The class name of the status model that holds all statuses.
     *
     * The model must be or extend `Spatie\ModelStatus\Status`.
     */
    'status_model' => Spatie\ModelStatus\Status::class,

    /*
     * The name of the column which holds the ID of the model related to the statuses.
     *
     * You can change this value if you have set a different name in the migration for the statuses table.
     */
    'model_primary_key_attribute' => 'model_id',

];

Usage

Add the HasStatuses trait to a model you like to use statuses on.

use Spatie\ModelStatus\HasStatuses;

class YourEloquentModel extends Model
{
    use HasStatuses;
}

Set a new status

You can set a new status like this:

$model->setStatus('status-name');

A reason for the status change can be passed as a second argument.

$model->setStatus('status-name', 'optional reason');

Retrieving statuses

You can get the current status of model:

$model->status; // returns a string with the name of the latest status

$model->status(); // returns the latest instance of `Spatie\ModelStatus\Status`

$model->latestStatus(); // equivalent to `$model->status()`

You can also get latest status of a given name:

$model->latestStatus('pending'); // returns an instance of `Spatie\ModelStatus\Status` that has the name `pending`

The following examples will return statusses of type status 1 or status 2, whichever is latest.

$lastStatus = $model->latestStatus(['status 1', 'status 2']);

// or alternatively...
$lastStatus = $model->latestStatus('status 1', 'status 2');

All associated statuses of a model can be retrieved like this:

$allStatuses = $model->statuses;

Retrieving models with a given latest state

The currentStatus scope will return models that have a status with the given name.

$allPendingModels = Model::currentStatus('pending');

//or array of statuses
$allPendingModels = Model::currentStatus(['pending', 'initiated']);
$allPendingModels = Model::currentStatus('pending', 'initiated');

Retrieving models without a given state

The otherCurrentStatus scope will return all models that do not have a status with the given name, including any model that does not have any statuses associated with them.

$allNonPendingModels = Model::otherCurrentStatus('pending');

You can also provide an array of status names to exclude from the query.

$allNonInitiatedOrPendingModels = Model::otherCurrentStatus(['initiated', 'pending']);

// or alternatively...
$allNonInitiatedOrPendingModels = Model::otherCurrentStatus('initiated', 'pending');

Validating a status before setting it

You can add custom validation when setting a status by overwriting the isValidStatus method:

public function isValidStatus(string $name, ?string $reason = null): bool
{
    ...

    if (! $condition) {
        return false;
    }

    return true;
}

If isValidStatus returns false a Spatie\ModelStatus\Exceptions\InvalidStatus exception will be thrown.

You may bypass validation with the forceSetStatus method:

$model->forceSetStatus('invalid-status-name');

Check if status has been assigned

You can check if a specific status has been set on the model at any time by using the hasEverHadStatus method:

$model->hasEverHadStatus('status 1');

Delete status from model

You can delete any given status that has been set on the model at any time by using the deleteStatus method:

Delete single status from model:

$model->deleteStatus('status 1');

Delete multiple statuses from model at once:

$model->deleteStatus(['status 1', 'status 2']);

Events

TheSpatie\ModelStatus\Events\StatusUpdated event will be dispatched when the status is updated.

namespace Spatie\ModelStatus\Events;

use Illuminate\Database\Eloquent\Model;
use Spatie\ModelStatus\Status;

class StatusUpdated
{
    /** @var \Spatie\ModelStatus\Status|null */
    public $oldStatus;

    /** @var \Spatie\ModelStatus\Status */
    public $newStatus;

    /** @var \Illuminate\Database\Eloquent\Model */
    public $model;

    public function __construct(?Status $oldStatus, Status $newStatus, Model $model)
    {
        $this->oldStatus = $oldStatus;

        $this->newStatus = $newStatus;

        $this->model = $model;
    }
}

Custom model and migration

You can change the model used by specifying a class name in the status_model key of the model-status config file.

You can change the column name used in the status table (model_id by default) when using a custom migration where you changed that. In that case, simply change the model_primary_key_attribute key of the model-status config file.

Testing

This package contains integration tests that are powered by orchestral/testbench.

You can run all tests with:

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].