GithubHelp home page GithubHelp logo

spatie / laravel-model-status Goto Github PK

View Code? Open in Web Editor NEW
902.0 15.0 81.0 256 KB

Easily add statuses to your models

Home Page: https://freek.dev/973-a-package-to-assign-statuses-to-eloquent-models

License: MIT License

PHP 100.00%
laravel eloquent model status php

laravel-model-status's Introduction

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/model-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`

Get all available status names for the model.

$statusNames = $model->getStatusNames(); // returns a collection of all available status names.

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;

This will check if the model has status:

$model->setStatus('status1');

$isStatusExist = $model->hasStatus('status1'); // return true
$isStatusExist = $model->hasStatus('status2'); // return false

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've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Credits

License

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

laravel-model-status's People

Contributors

adrianmrn avatar alexmanase avatar alexvanderbist avatar amaelftah avatar brendt avatar dabernathy89 avatar freekmurze avatar laravel-shift avatar lostincode avatar m1crogravity avatar marcvdm avatar pascalbaljet avatar patinthehat avatar polmtn avatar reado avatar rizky92 avatar rubenvanassche avatar rzb avatar sebastiandedeyne avatar shuvroroy avatar supianidz avatar tal7aouy avatar therouv avatar tvke avatar vdbelt avatar vinlim avatar vmitchell85 avatar vpratfr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-model-status's Issues

Eloquent relations with

How can i to use with eloquent relations with ?
For now this helps me

    // model 
    public function currentStatus()
    {
        return $this->MorphOne(
            $this->getStatusModelClassName(),
            'model',
            'model_type',
            $this->getModelKeyColumnName()
        )
            ->latest('id');
    }
    // controller 
    User::with('currentStatus')->get();

Integrity constraint violation: 1048 Column 'model_id' cannot be null

I am trying to use this package to monitor the status of my Orders.

  1. My Order model has the HasStatuses trait
  2. The statuses table is migrated

In my OrderController I do:

$order = new Order();
$order->description = $request->description;
$order->setStatus($request->status_name, $request->status_reason);

Both $request->status_name and $request->status_reason are coming from a form.

When I try to post the form I get the following error:

Integrity constraint violation: 1048 Column 'model_id' cannot be null

As I see from the response the model_type is App\Order which in my mind is the correct value. Why isn't the model_id added into the query when doing $order->setStatus(...)?

Thanks!

delete statuses on delte model?

Hi,
does/can this package kep statuses in sync with model deletions using forgein key assignment? if so, how does it work becasue it's not doing in my app.

if not, what would be the preferred place to get and delete any statuses please?
ty.

How to store statuses for the models with HasStatuses trait ?

Hi, I just discovered the package but I'm not sure on how to store the statuses efficiently/smartly. Should I make them a property array in the Model or put them in a/multiple separate data table(s) ?

What's your advice on that ?

Best regards,

model_has_statuses doesn't exist

Hello,

I got this error. I think it's a bug.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'makales.model_has_statuses' doesn't exist (SQL: select statuses.*, model_has_statuses.model_id as pivot_model_id, model_has_statuses.status_id as pivot_status_id, model_has_statuses.model_type as pivot_model_type from statuses inner join model_has_statuses on statuses.id = model_has_statuses.status_id where model_has_statuses.model_id = 1 and model_has_statuses.model_type = App\Models\Post limit 1)

Application Name ......................................................................................................................... Laravel
Laravel Version ........................................................................................................................... 9.25.1
PHP Version ................................................................................................................................ 8.1.9
Composer Version ........................................................................................................................... 2.4.0
Environment ................................................................................................................................ local
Debug Mode ............................................................................................................................... ENABLED

Add default status functionality

implement default status functionality by writing a mthod in the HasStatuses trait that can be overriden in the model returning the default status. The default status is set whenever the model is created.

Delete al statuses

How can I delete all the statuses without defining them?

The statuses are dynamic in my system and on destroy I want to remove them all.

QueryBuilder::setStatus does not exitst

Hi, please help me, i have a something error in my first try at this package. I have insert the UseStatuses in model, but i get error.

My controller is :

public function statuses(PinjamRuang $pinjamruang)
{
    $pinjamruangs = $pinjamruang->where('id',1)->setStatus('pending');
}

And I have error :
"Method Illuminate\Database\Query\Builder::setStatus does not exist."

PinjamRuang is my model and I have inserted useHasStatuses like this :

use Illuminate\Database\Eloquent\Model;
use Spatie\ModelStatus\HasStatuses;
class PinjamRuang extends Model
{
use HasStatuses;
protected $fillable = [
'user_id', 'ruang_id', 'waktu_mulai', 'waktu_selesai', 'kegiatan', 'lampiran',
];
}

I also do vendor publish like in the tutorial, but the error still come.

Laravel 5.4

Sorry but how can i use this in Laravel 5.4? thanks

OrderBy

Hi, thanks for creating this.

Is it possible to sort a collection of models by the latest status?

InvalidStatusModel on clean install

> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi

   Symfony\Component\Debug\Exception\FatalThrowableError  : Argument 1 passed to Spatie\ModelStatus\Exceptions\InvalidStatusModel::create() must be of the type string, null given, called in /srv/http/project/vendor/spatie/laravel-model-status/src/ModelStatusServiceProvider.php on line 41

  at /srv/http/project/vendor/spatie/laravel-model-status/src/Exceptions/InvalidStatusModel.php:9
     5| use Exception;
     6| 
     7| class InvalidStatusModel extends Exception
     8| {
  >  9|     public static function create(string $model): self
    10|     {
    11|         return new self("The model `{$model}` is invalid. A valid model must extend the model \Spatie\ModelStatus\Status.");
    12|     }
    13| }

  Exception trace:

  1   Spatie\ModelStatus\Exceptions\InvalidStatusModel::create()
      /srv/http/project/vendor/spatie/laravel-model-status/src/ModelStatusServiceProvider.php:41

  2   Spatie\ModelStatus\ModelStatusServiceProvider::guardAgainstInvalidStatusModel()
      /srv/http/project/vendor/spatie/laravel-model-status/src/ModelStatusServiceProvider.php:28

  Please use the argument -v to see more details.

How to use with multiple status for different role?

Hi just asking some idea on how to approach this use case.

For example

Model current status is PENDING PICKUP, and the the Manager user click the button PICKUP.

  1. The status for Manager user now is IN PROGRESS.

  2. The status for normal user is PICKED UP.

Question

  1. Do we store both status?

  2. If yes, how do we differentiate which STATUS is for which user role? I'm thinking maybe a custom column in the statuses table called status_roles

Thanks

Properties?

Wondering about the possibility of storing additional properties, not just a reason. I'm thinking similar to the properties of your activity log package. I'm not 100% sure if that's a better approach than others that you could take to accomplish the same thing (like a related table or something). The project I'm working on right now stores some additional information with some of the status changes. We don't need to search on it or anything, so having it pretty simple like the activity log properties would make sense. But if you did need to search on the specifics, a more customized approach would make sense.

Also, you guys are amazing! :)

Call to a member function getRelated() on null

I have this successfully installed and ran migration to create statues table as well. However when I run I get below error.

Error
Call to a member function getRelated() on null

Query from the debug panel is pasted below for more information.

select * from "statuses" where "statuses"."model_id" is null and "statuses"."model_id" is not null and "statuses"."model_type" = ? order by "id" desc limit 1

Any reason not to add an accessor?

I note that we can use $myModel->status() to get the latest status,

Could we add a getStatusAttribute() function that would do the same as ->status(), but would allow us to just to $myModel->status I believe this would play better with the $appends` property on Eloquent models as well.

Happy to contribute if approved.

Question about filtering by latest status?

Any suggestions on doing the following?

Get a list of users whose latest status in set S is the status T.

Currently, I am getting a list of all users and then filtering in a collection using $model->latestStatus($setS)->name == $T. This works, but ideally, this would be done using the Eloquent ORM (instead of filtering a collection) for performance reasons.

So, I am looking for an Eloquent example, that could be turned into a scopeLatestStatusEquals($T, ...$setS).

I think this would be useful to others as well, I'm just a bit lost at writing the Eloquent query for it.

Many statuses per model?

Can this package assign multiple statuses to an Eloquent model?

For example, typical case scenario in a business application. Let's say we have an Invoice model, which describes an issued invoice. In a multistage business application this model can have multiple statuses at the point of a lifetime of the invoice:

  • I can have a general invoice status: Issued, Signed, Sent, etc..
  • I can gave a finical status that tells me invoice has been paid or not

Then if we look at order mode can have a similar scenarios. Can have multiple statuses, depending from which side of organisation you are looking at. Marketing people can have its own statuses, production people its own, shipping people its own, and so on...

Custom attribute name for status

I already have an existing status attribute on my model that represents a different meaning and cannot be modified/ renamed.
Can I rename the package's status attribute?

eg. Model User
User->status --- existing attribute
User->spatie_custom_status --- an instance of \Spatie\ModelStatus\Status

Many languages

This will be support to many languages in status name?

Best Way To Append Status Since Custom Attribute Update

Since the update with the custom status attribute, I am no longer able to easily add status as an Eloquent Model append.

I am currently using Laravel Model Status v1.14.0 and Laravel v9.52x.

I added the new status_attribute key in the config file array, which is set to the default value of status.

My model has status added in the $appends class var.

Previously, this was all that was needed, and the status attribute appears in my calls to $model->toArray() and $model->toJson(). In my particular case those calls are done behind the scenes with InertiaJs.

However, since the update, the underlying method was removed, so I am now getting the error Call to undefined method App\Models\Event::getStatusAttribute().

Is there a new best way to handle status appends going forward? Or is this unintended behavior?

does it provide sync status?

Thanks for your great work.

I have a problem to sync status to new one.

How can I clean up old statues of model and add new ones. Something like

Model->syncStatus(['pending'])

Does this package provide only setStatus() method? (only adding status)
How can I remove or unset old status?

Using select with with('statuses') return empty array

$data = Model::with('statuses')->get();
return response()->json(['data' => $data]);

works fine, meanwhile

$data = Model::with('statuses:id,name,reason')->get();
return response()->json(['data' => $data]);

return empty array

adding causer_id to statuses table

Hi, I'm a pretty newbie on this… is there any way that I could add a causer_id to the statuses table and auto fill it with the logged user id (\Auth::id())?

If you could, please send me any link that points out how to do it, or a sample code that I can use to understand and learn more.

thanks!

RA

Can get status

I want to only get list of users with pending

$all = User::currentStatus('pending');
 $user = $all->latest()->get();

Is there a way to eager load for an API resource?

I've defined an API resource where I want to return the status of the model, but I'm getting an N+1 because it's fetching the status for each model individually. Is there a way to eager load this?

return [
				'id'                         => $this->id,
				'created_at'                 => $this->created_at,
				'updated_at'                 => $this->updated_at,
				'initiated_by'               => new UserResource($this->initiated_by),
				'amount'                     => $this->amount,
				'icon'                       => $this->icon,
				'reference'                  => $this->reference,
				'status'                     => $this->status,
]

Event on status change

Hi,

Do you think events for status changes should be part of the package?

I have this currently implemented on a per-model basis, but wondering if that would be worth including in the package.

Like StatusUpdated($model, $oldStatus, $newStatus)

Obtain last status of a model through SQL

Is there a (easy ?) way to get the last status of a model with a SQL query ?
I would like to use sql queries to get all my models and their current status in an extract.

i cant see the approval person detail

i want to be able to pass in the id of the auth user so that at the end of the day when am pulling the statuses attached to the model i can get the detail of that user who made comment

by the way I would like to thank the creators of this package its really nice thanks alot though its lacking this feature anyone to guide me how to achieve this

Nova Field

Hello,

Thank you for this great package! I would like to use the statuses in a Nova field for my model. I'm not sure how to implement this. I have tried the 'morph fields' but I can't seem to render the field.

Thank you in advance!

Filter by status using spatie/laravel-query-builder

I am trying to use this together the spatie/laravel-query-builder package, how I do to build a scoped filter by status?

I tried something like this, but it doesn't work:

    public function scopeStatus($query, $status)
    {
        return Model::currentStatus($status);
    }

Using another key name than 'model_id'

In our app, we use UUIDs as ids.

For consistency within the application, we suffix the foreign key names with _uuid instead of _id as our primary key column is 'uuid'.

We can easily update the migration files to change the $table->morphsTo('model') to use a different name and type for the schema.

However, it is more difficult to let the HasStatus trait know about it.

So, currently I am stuck with either :

  • Redefining most of the trait (not so great as I would copy-paste all methods including the ones which do not show any issues)
  • Sticking with model_id as column name. But does not feel right/consistent when looking at the whole application DB schema.

Possible way to solve it (unless you have a better idea) :

Allow a custom column name within the traits (could be a property which could be set in the class, like private $permissionModelForeignColumn = 'model_uuid'; and check if that propery is set in the relationship method (defaulting to current name if not)

[SUGGESTION] SaveManyStatuses

Recently while I was using the package I've needed to save/update a bunch of records(10k+ in one go) at the same time and their corresponding statuses. However, I haven’t founded any efficient way of doing that using the package built-in capabilities. So i've come up with this Trait:

https://gist.github.com/andresayej/d265986c38255b3bb4a418fe33bab32b

So, if you use this Trait alongside the HasStatuses Trait in your model you can do stuff like this:

Post::saveManyStatuses('Draft', ['4', '9', '13', '17']);

or

User::saveManyStatuses('Promoted', ['1', '2', '3', '4'], 'Optional reason for promotion status');

or

Comment::saveManyStatuses('Review', ['21', '24', '81', '97'], 'Optional reason for review status', 500);

@freekmurze is this something worth proceeding if you are willing to include it in the core of the package?

If yes, my roadmap for this feature is:

  • Write tests
  • Find a way to strip down all eager loaded relationships on the model (if defined in the model's $with array) as to better optimize the performance of the number of queries and the memory usage. (Stumbled upon this myself, so sounds like an edge case for more people )
  • Find a way to support SoftDeletes with an optional parameter in the function. Something like: saveManyStatuses('Deleted', $ids, null, null, true)
  • the default ChunkNumber can be configured from the package config file
  • maybe refactor to collections?

You can achieve this by using your own custom model and [eloquent models events](https://laravel.com/docs/5.6/eloquent).

          You can achieve this by using your own custom model and [eloquent models events](https://laravel.com/docs/5.6/eloquent).
  1. Create a new model class like this (untested):
namespace App\Models;

class YourStatusModel extends \Spatie\ModelStatus\Status

public static function boot()
{
   // this function will automatically be executed by Laravel when a new `Status` is being created.
    static::creating(function(YourStatusModel $status) {
        $status->causer_id = optional(auth()->user())->id;
    });
}
  1. Set that class in the status_model key of the model-status config file.

  2. Create a migration that adds caused_id to the statuses table.

  3. Profit!

Originally posted by @freekmurze in #38 (comment)

Custom isValidStatus() Not Overriding Trait Implementation – Need Assistance

I'm using the isValidStatus() method in my model, which extends Spatie\ModelStatus\Status, but my custom function is not working.

<?php

namespace App\Models;

use Illuminate\Contracts\Database\Eloquent\Builder;
use Spatie\ModelStatus\HasStatuses;
use Spatie\ModelStatus\Status as SpatieModelStatus;

class StatusHook extends SpatieModelStatus
{
    use HasStatuses;

    public function isValidStatus(string $name, ?string $reason = null): bool
    {
        return StatusType::where('slug', $name)->exists();
    }
}

Use with models that have a uuid instead of int

Is it possible to use this package with models that have a uuid as their ID rather than an int? I'm getting the following error when trying to set a status:

Illuminate\Database\QueryException : SQLSTATE[01000]: Warning: 1265 Data truncated for column 'model_id' at row 1 (SQL: insert into `statuses` (`name`, `reason`, `model_id`, `model_type`, `updated_at`, `created_at`) values (departed, Departed, 6eff0175-ec09-4ab2-8af1-27bc37230208, App\Flight, 2019-03-24 14:54:39, 2019-03-24 14:54:39))

Accessing status() after a call to setStatus does not give you current status.

Lets say the current status for my model is "Testing 123".

$m = Model::find(1);
echo $m->status;

would yield:

Testing 123

as expected. However if you:

$m = Model::find(1);
echo $m->status;
$m->setStatus('Testing 1234');
echo $m->status;

You would see:

Testing 123
Testing 123

I realize I could just $m->load('statuses') , but it seems like it would be helpful if setStatus did this automatically.

Adding an index to the status for faster retrieval

Hey spatie team,
Love y'all's Laravel work. Any interest or thought on indexing the status column? Is that something you want to leave to users to do or should this package implement it?

I'm just concerned that looking up my model by status could get slow if I have lots of statuses.

Performance improvements?

In attempting to use this package, I was unable to get any reasonable performance for searching based on status. Even after adding an index to the name column, I was left with a query that ended up taking 4 seconds to get a paginated list of models with that status. To be fair I have about 750k records with at least half having a status. I guess my question is if there is any other performance improvements that can be had or if this is just the best that can be attained. If nothing can be improved then I would say this package would only be suitable for smaller datasets rather than anything on the larger end.

That being said Love what you guys are doing and probably are using almost every laravel package you guys have made! (Didn't want to be ALL doom and gloom)

can update statuses of models collection (Question)

I can get collection of models by

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

How can I update collection of models statuses ?

 $updateCollection = $model->currentStatus('pending')->setStatus('approved');

Thanks.

Implement enum based statuses

I've used this package before, it's great, but something I always end up doing is wrapping it around a different trait to add more restriction to how my statuses are set.

Would it be a good idea if a solution that uses PHP Enums was used, to apply this restriction?
Here's an example usage

$post->setStatus(PostStatus::PENDING, 'needs verification');
$post->status; //returns PostEnum Instance

I'm willing to work on this feature.

Default status

Hi @freekmurze.

I know this was addressed in the issue #47, but I would like to know if you are willing to consider something like the following to handle default status per model:

trait HasStatuses
{
  public function bootHasStatuses()
  {
     if (static::DEFAULT_STATUS) {
       static::created(function($myModel) {
         $myModel->setStatus(static::DEFAULT_STATUS);
       });
     }
  }
  ...
}

class MyModel
{
  use HasStatuses;

  const DEFAULT_STATUS = 'pending';
}

Thanks!

Multiple models with statuses to Inertia

Currently i have a controller, in the index method im sending to Inertia a collection of Rooms, like so:

return Inertia::render('Dashboard', [
    'rooms' => Room::get(),
]);    

What would be the best way to also send the current status of each room?

At the moment what I do is simply use ::with('statuses') like this:

return Inertia::render('Dashboard', [
    'rooms' => Room::with('statuses')->get(),
]);    

The only problem with doing it this way would be that it sends all the statuses the model has instead of just the current status.

Any ideas? Im guessing i could groupBy model_id or something like that 🤔

Querying by intervals

I have an use case that might be somewhat common among dev's using this package, so I'm curious how people have approached this.

Say I have products hasMany items (item representing an ordered product). Product can be active or inactive. Then I want to know how many times each product was ordered in the last N days that it's been active.

Of course I can fetch all statuses for each product, iterate them, count days, etc. But I'm looking for a more eloquent/query-builder way with as few queries as possible.

I think it'd be also nice if this package offered something like $model->statusDuration('status-name') to easily find out how much time the model has been with the given status.

Opinions?

Allow setting statuses without the `isValidStatus` check

When testing you might want to bypass the isValidStatus check. For example skipping the first n-steps when registering a user for a test.

I propose a allowInvalidStatus() method that can be chained together with setStatus():

$user->allowInvalidStatus()->setStatus('activated');

An alternative would be something like forceSetStatus()

$user->forceSetStatus('activated');

How use this in project real? i need examples.

How to use this to create a status of an order?

I have a screen where I see the details of a specific request, being that I need a status, for example ... Paid, Delivered and these things.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.