Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Cast Eloquent Pivot Parameters?

I have the following Eloquent Models with relationships:

class Lead extends Model  {     public function contacts()      {         return $this->belongsToMany('App\Contact')                     ->withPivot('is_primary');     } }  class Contact extends Model  {     public function leads()      {         return $this->belongsToMany('App\Lead')                     ->withPivot('is_primary');     } } 

The pivot table contains an additional param (is_primary) that marks a relationship as the primary. Currently, I see returns like this when I query for a contact:

{     "id": 565,     "leads": [         {             "id": 349,              "pivot": {                 "contact_id": "565",                 "lead_id": "349",                 "is_primary": "0"              }         }     ] } 

Is there a way to cast the is_primary in that to a boolean? I've tried adding it to the $casts array of both models but that did not change anything.

like image 986
Josh Avatar asked May 13 '15 22:05

Josh


1 Answers

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 Illuminate\Database\Eloquent\Relations\Pivot class. On this class you may define your $casts property.

<?php  namespace App;  use Illuminate\Database\Eloquent\Relations\Pivot;  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 Illuminate\Database\Eloquent\Model;  class Lead extends Model {     public function contacts()     {         return $this->belongsToMany('App\Contact')->using('App\CustomPivot');     } } 

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.

like image 110
Jonathon Avatar answered Sep 20 '22 21:09

Jonathon