Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

A package to assign statuses to Eloquent models

Original – by Freek Van der Herten – 2 minute read

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, only adding a single field won't cut it. To handle these cases, our team has created a package called laravel-model-status.

After installing the package you must add the HasStatuses trait to all models that need to have statuses.

You can set a new status like this:

$model->setStatus('my first status');

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

$model->setStatus('my second status', 'I found a reason');

There are a few options to retrieve the latest status:

$model->status; // returns 'my second status'
$model->status(); // returns the latest instance of `Spatie\ModelStatus\Status`
$model->status()->reason; // returns 'I found a reason'

Of course you can also retrieve the whole status history of a model.

$model->statuses; // returns a collection of all statuses

The package provides a scope to retrieve all models that have a given status.

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

To know more about the package, head over the the readme on GitHub. The principle author of package is our intern Thomas Verhelst. Be sure to also check out the other Laravel packages our team has previously made.

Stay up to date with all things Laravel, PHP, and JavaScript.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.

Comments

What are your thoughts on "A package to assign statuses to Eloquent models"?

Comments powered by Laravel Comments
Want to join the conversation? Log in or create an account to post a comment.