In Laravel 5.4.14 this issue has been resolved. You are able to define a custom pivot model and tell your relationships to use this custom model when they are defined. See the documentation, under the heading Defining Custom Intermediate Table Models.
To do this you need to create a class to represent your pivot table and have it extend the IlluminateDatabaseEloquentRelationsPivot
class. On this class you may define your $casts
property.
<?php
namespace App;
use IlluminateDatabaseEloquentRelationsPivot;
class CustomPivot extends Pivot
{
protected $casts = [
'is_primary' => 'boolean'
];
}
You can then use the using
method on the BelongsToMany
relationship to tell Laravel that you want your pivot to use the specified custom pivot model.
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Lead extends Model
{
public function contacts()
{
return $this->belongsToMany('AppContact')->using('AppCustomPivot');
}
}
Now, whenever you access your pivot by using ->pivot
, you should find that it is an instance of your custom pivot class and the $casts
property should be honoured.
Update 1st June 2017
The issue raised in the comments by @cdwyer regarding updating the pivot table using the usual sync
/attach
/save
methods is expected to be fixed in Laravel 5.5 which is due to be released next month (July 2017).
See Taylor's comment at the bottom of this bug report and his commit, fixing the issue here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…