Laravel 5.5 Pivot Casting

Tutorials

July 5th, 2017

Laravel 5.5 Pivot Casting

A new addition to Laravel 5.5 will add support for pivot table casts when inserting & updating data on an intermediate table model.

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:

namespace App;
 
use Illuminate\Database\Eloquent\Model;
 
class User extends Model
{
/**
* The attributes that should be cast to native types.
* @var array
*/
protected $casts = [
'is_admin' => 'boolean',
];
}

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.

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:

dd( $runner->pivot->splits );
 
// Example:
[
'Lap 1' => 150,
'Lap 2' => 163,
'Lap 3' => 146
]

But when creating or updating the pivot model, you still have to cast it manually:

// Cast first...
$splits = $splits->toJson();
 
// ...then attach:
$runner->races()->attach($raceId, ['splits' => $splits]);

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 is no longer necessary.

Filed in:

Casey Dwyer

I craft digital goodies for awesome people. Kansas native, K-State grad, farm kid, notorious sweet-tooth.