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
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.
@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.
@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);
}
}