Around the 'net
This article was originally written for Laravel News—check out the original post or the pull request on Laravel's framework repo for more details.
A new addition to Laravel 5.5 will add support for pivot table casts when inserting & updating data on an intermediate table model.
Overview
Currently, the $casts
you set on a traditional model will work in both directions; any model that extends the Eloquent\Model
class will look for a $casts
property and convert the specified attributes to a data type when reading and writing. For example, from the documentation:
1namespace App; 2 3use Illuminate\Database\Eloquent\Model; 4 5class User extends Model 6{ 7 /** 8 * The attributes that should be cast to native types. 9 * @var array10 */11 protected $casts = [12 'is_admin' => 'boolean',13 ];14}
In Laravel 5.4, Taylor added the ability to define a $casts
property on your custom pivot models as well, but it only applied those $casts
when reading the data—no conversion was performed when inserting or updating an attribute.
Before
For example, let’s say you have a Runner model and a Race model. One runner can have many races, and one race can have many runners. Let’s call our pivot model a RaceRunner, which will include a splits
array with a varying number of individual lap times (depending on the length of the race, and stored in seconds) in addition to the required runner_id
and race_id
.
The splits
array is serialized as JSON in the race_runner
table, so if you defined splits as an array in the $casts
of your RaceRunner pivot model, then the following will dump an array:
1dd( $runner->pivot->splits );2// Outputs:3[4 'Lap 1' => 150,5 'Lap 2' => 163,6 'Lap 3' => 1467]
But when creating or updating the pivot model, you still have to cast it manually:
1// Cast first...2$splits = $splits->toJson();3 4// ...then attach:5$runner->races()->attach($raceId, ['splits' => $splits]);
After
Now with Laravel 5.5, the $casts
property on the Eloquent\Model
and Eloquent\Relations\Pivot
classes will behave the same. 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 block is no longer necessary. Happy casting! 🎣