Closed
Description
#- 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_encode
d 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) ""{}""
Metadata
Metadata
Assignees
Labels
No labels