Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

madsem's avatar

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.

0 likes
5 replies
Snapey's avatar

Aren't casts only for getting data from the model - nothing to do with setting data.

madsem's avatar

Well that is kind of my question :)

https://laravel-news.com/laravel-5-5-pivot-casting says it's for setting and getting data as far as I read this...

Laravel will “respect” your casts on both, whether you’re reading, inserting or updating data. This will make the attach, sync and save methods available to pivot models. Applying this new feature to our example above, the // Cast first... code is no longer necessary.
madsem's avatar

And Taylor Otwell writes

This updates Laravel to respect casts definitions on custom pivot
models when using the ->using() method on a BelongsToMany relationship.

And then I test it but it only seems to work when using $casts and a mutator, which makes me think I did something wrong, or at least there is a better more standard way for what i want to do?

Snapey's avatar

ok, but how could it possibly know that 'on' is your boolean for 1 ?

madsem's avatar

That makes a lot of sense yeah. Seems I overthought this a little and should simply convert it directly in my code when I create it.

Please or to participate in this conversation.