Aren't casts only for getting data from the model - nothing to do with setting data.
Apr 21, 2018
5
Level 4
Custom Pivot Class: Do we really need $casts AND a mutator?
I made a custom Pivot class, updated my relationships to ->using(CustomPivot::class)
because I want to automatically cast a checkbox value from 'on' to boolean true.
It didn't work and always tried to save the 'on' value until I added a mutator, like so:
namespace Modules\Core\Entities\Pivots;
use Illuminate\Database\Eloquent\Relations\Pivot;
class CustomPivot extends Pivot
{
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'attribute_name' => 'boolean'
];
public function setAttributeNameAttribute($value)
{
$this->attributes['attribute_name'] = ($value == 'on');
}
}
My question now, shouldn't this work without the mutator and just by adding the $casts property?
Everything I read, like https://github.com/laravel/framework/pull/19335 to me sounds like all that is needed is ->using() and $casts.
But now I'm unsure if what I did is a "mistake" and could/should be handled differently.
Please or to participate in this conversation.