如何将 Laravel Eloquent 里的数值属性强制转换为布尔类型?

Laravel

I wanted to return a value that gets saved as an integer in the 'active' column in a database table as a boolean.

My initial ugly solution was to change the attribute like this (that is to force the return type to boolean):

public function getActiveAttribute($value): bool
{
       return $value;
}

My code reviewer found a much better solution:

https://learnku.com/docs/laravel/6.x/eloquent-muta...

So I replaced above code in the Eloquent model with this:

 protected $casts = [
        'active' => 'boolean',
    ];
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://dev.to/programmingdecoded/castin...

译文地址:https://learnku.com/laravel/t/41713

本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!