Reputation: 115
I'm developing a blog using Laravel and I'm trying to use the BenSampo Enum package. Everything seems to work when saving a blog post but the issue arises when casting the post_status field as an integer. It is being cast as a string, though I've specifically set the cast as an integer on the model. So I get the output below instead:
Cannot construct an instance of PostStatusEnum using the value (string) 1
. Possible values are [0, 1, 2, 3, 4].
I did quite a bit of research online and found a trait that would make sure to return the cast as an integer. I modified it for this purpose and it indeed works as intended but it collides with the BenSampo\Enum\Traits\CastsEnums trait.
When creating the post, I'm attaching the status via an observer based on a certain condition, it is not coming through a form, so I can't really validate it (haven't found a way yet, at least). I basically want to do $post_status = $post->post_status on the controller and get whichever one was saved (or whichever the model has at a given time). So, instead of trying to hack that package, I'm now trying to create a mutator to make sure the post_status field gets saved as an integer to start with but I'm having a bit of difficulty with that as well. The code below doesn't seem to do anything, what am I missing?
public function setPostStatusAttribute($value)
{
$this->attributes['post_status'] = integer($value);
}
For reference, this is what I have on the model and migration, have also imported the required namespaces:
protected $enumCasts = [
'post_status' => PostStatusEnum::class,
];
protected $casts = [
'post_status' => 'int', // I've also tried integer. Have also tried putting it above the
$enumCasts
];
//migration
$table->unsignedInteger('post_status'); //have also tried integer and tinyInteger.
I also tried the Spatie Enums package, with the Laravel extension, that one returns the value as an integer but also ran into issues with that one trying to display the field in the show method.
Upvotes: 0
Views: 5573
Reputation: 14251
$this->attributes['post_status'] = integer($value);
I don't know if this should even work, as far as I know, there isn't an integer(...)
helper.
Try casting instead:
$this->attributes['post_status'] = (int) $value;
I haven't used the first package that you mentioned, but the spatie/laravel-enum yes. In that package (that, in turn, uses spatie/enum underneath) you can just do this:
# Post.php
protected $enums = [
'post_status' => PostStatusEnum::class,
'another_field' => AnotherFieldEnum::class . ':nullable',
// the last bit is to accept nullable values ^^^^^^^^^
];
In case you want to use accessors:
public function getPostStatusAttribute($postStatus)
{
return PostStatusEnum::make($postStatus);
}
Upvotes: 1