2

I have a Model called User and another Model called Roles and they are linked with each other through a belongsToMany relationship. But I needed to cast certain pivot attributes so I used a custom pivot class RoleUserPivot which basically looks like follows:

...
use Illuminate\Database\Eloquent\Relations\Pivot;

class RoleUserPivot extends Pivot
{

    protected $casts = [
        'active' => 'boolean',
        'permissions' => 'array',
    ];
}
...

The relationship definition in User and Role models is as follows:

...
// User Model
public function roles()
{
    return $this
        ->belongsToMany('App\Role')
        ->withPivot(
            'active',
            'permissions'
        );
}

public function newPivot(Model $parent, array $attributes, $table, $exists)
{
    if ($parent instanceof Role) {
        return new RoleUserPivot($parent, $attributes, $table, $exists);
    }

    return parent::newPivot($parent, $attributes, $table, $exists);
}
...

And similarly:

...
// Role Model
public function users()
{
    return $this
        ->belongsToMany('App\User')
        ->withPivot(
            'active',
            'permissions'
        );
}

public function newPivot(Model $parent, array $attributes, $table, $exists)
{
    if ($parent instanceof User) {
        return new RoleUserPivot($parent, $attributes, $table, $exists);
    }

    return parent::newPivot($parent, $attributes, $table, $exists);
}
...

The problem I am having is, while the active field is properly cast to boolean, the permissions field is not cast to array, instead the same string in the database is returned. I assure that the pivot table is properly setup and permissions column is MySQL TEXT column.

Currently I am using Laravel 5.1.16 (LTS).

amith.gotamey
  • 968
  • 8
  • 14
  • That's strange, that all looks correct to me… Is it definitely not working in both directions? Have you checked that the relationships definitely both return the `RoleUserPivot` object? – James Flight Sep 15 '15 at 07:22
  • @JamesFlight yup `RoleUserPivot` is returned and the dump also contains that the `cast` is present. I don't know what the problem is ... tried to fiddle with the `Illuminate\Database\Eloquent\Model@castAttribute` also, its just a `json_decode` function which works in `artisan tinker` but not in the `castAttribute` method. Maybe I'm missing a silly thing somewhere. Will update this if I get any solution(s) – amith.gotamey Sep 15 '15 at 08:52

0 Answers0