Skip to content

Casts property on custom pivot model is not honored for JSON castable attributes #18135

Closed
@jrhenderson1988

Description

@jrhenderson1988

#- Laravel Version: 5.4.11

  • PHP Version: 7.0.15
  • Database Driver & Version: MySQL driver - Maria DB 10.2.3

Description:

When defining a BelongsToMany relationship on an Eloquent model and specifying a custom pivot model with the using method, I am finding that the $casts property on the custom pivot model is not honoured for JSON castable attributes.

Where I have specified a JSON cast on an attribute for the pivot model, I am finding that a string is returned (The JSON itself) when attempting to access that property.

Steps To Reproduce:

Network model

class Network extends Model
{
    public function clients()
    {
        return $this->belongsToMany(Client::class)
            ->using(ClientNetworkPivot::class)
            ->withPivot(['settings']);
    }
}

Client model

class Client extends Model
{
    public function network()
    {
        return $this->belongsToMany(Network::class)
            ->using(ClientNetworkPivot::class)
            ->withPivot(['settings']);
    }
}

Custom pivot model

class ClientNetworkPivot extends Pivot
{
    protected $casts = [
        'settings' => 'array'
    ];
}

Steps

$client = Client::find(1);

$networks = $client->networks;
foreach ($networks as $network) {
    var_dump(get_class($network->pivot), $network->pivot->settings);
}

Expected output

string(36) "App\Models\Pivots\ClientNetworkPivot"
array(0) {
}

Actual output

string(36) "App\Models\Pivots\ClientNetworkPivot"
string(2) "{}"

Additional Information

It seems that in this case, the attribute is being json_encoded again when it's being set in the pivot model. By running var_dump($network->pivot->getAttributes()['settings']); I am getting the following output string(4) ""{}""

#18149

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions