moimichel's avatar

How to use some php constants in laravel

Hi. Happy new year to everybody. I would like to use a field (integer) in a database as a status of the record. It can be something like this:

public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
                $table->string('title');
        $table->text('summary')->nullable();
        $table->text('body');
        $table->integer('status'); // 1=draft, 2=published, 3=deleted, and so on ....
    });
    }

Where (the best place) can I define those constants: DRAFT = 1 PUBLISHED = 2 DELETED = 3

Thanks in advance.

0 likes
5 replies
Snapey's avatar

You can set the column as an enum with those strings within the database and then just store 'DRAFT' etc and it will be converted to the value for you.

mdeorue's avatar

I put this in the model, like

const DRAFT = 1; const PUBLISHED = 2; ...

and in the Controller I use,

$post = new Post(); $status = $post::DRAFT;

or the scopes in the model,

public function published($query) { return $query->where('status', self::PUBLISHED); }

etc...

2 likes
tykus's avatar

As I see it, you have a number of options (as above) depending on your needs; for example, a plain old PHP class which defines the constants

class Status
{
    const DRAFT = 1;
    const PUBLISHED = 2;
    const DELETED = 3;
}

You would use thusly:

$post->status = Status::DRAFT;
1 like
moimichel's avatar

Thank you all for those tips.

@Snapey I like this approach, but since it is depending on database design, every time I need to add or delete a new "status" I would need to re-migrate the database.

@mdeorue This is the easiest and more convenient way for me. Those constants are related to a model and that is a good place to insert them.

@tykus If "status" is needed by more than 1 table, this can be a good solution.

This is my very humble point of view. Comments are more than welcome.

1 like
martinbean's avatar

@moimichel Enums are typically advocated against, one of the reasons you mention.

You can either put the constants in the related model, or its own dedicated class:

class Post extends Model
{
    const STATUS_DRAFT = 1;
    const STATUS_PUBLISHED = 2;

    public function scopeDrafts($query)
    {
        return $query->whereStatus(static::STATUS_DRAFT);
    }

    public function scopePublished($query)
    {
        return $query->whereStatus(static::STATUS_PUBLISHED);
    }
}
class PostStatus
{
    const DRAFT = 1;
    const PUBLISHED = 2;
}

class Post extends Model
{
    public function scopeDrafts($query)
    {
        return $query->whereStatus(PostStatus::DRAFT);
    }

    public function scopePublished($query)
    {
        return $query->whereStatus(PostStatus::PUBLISHED);
    }
}
4 likes

Please or to participate in this conversation.