php - How To Cast Eloquent Pivot Parameters? -
i have following eloquent models 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 additional param (is_primary) marks relationship primary. currently, see returns when query contact:
{ "id": 565, "leads": [ { "id": 349, "pivot": { "contact_id": "565", "lead_id": "349", "is_primary": "0" } } ] } is there way cast is_primary in boolean? i've tried adding $casts array of both models did not change anything.
since attribute on pivot table, using $casts attribute won't work on either lead or contact model.
one thing can try, however, use custom pivot model $casts attribute defined. documentation on custom pivot models here. basically, create new pivot model customizations, , update lead , contact models use custom pivot model instead of base one.
first, create custom pivot model extends base pivot model:
<?php namespace app; use illuminate\database\eloquent\relations\pivot; class primarypivot extends pivot { protected $casts = ['is_primary' => 'boolean']; } now, override newpivot() method on lead , contact models:
class lead extends model { public function newpivot(model $parent, array $attributes, $table, $exists) { return new \app\primarypivot($parent, $attributes, $table, $exists); } } class contact extends model { public function newpivot(model $parent, array $attributes, $table, $exists) { return new \app\primarypivot($parent, $attributes, $table, $exists); } }
Comments
Post a Comment