Please remove the pivot attribute of a "jsonified" model. Since it makes an api "fatter" then needed.
{
id: 87,
title: "Title",
pivot: {
user_id: 1,
photo_id: 87
}
Add it to your "hidden" array.
You're right!
For future fellow Laravel 4.1.x journeymen, please refer to the Docs under Eloquent / Converting to Arrays or JSON on how to use the hidden
array.
<?php
class User extends Eloquent
{
protected $hidden = array('pivot');
}
But how do you hide a specific field within pivot table, like
<?php
class User extends Eloquent
{
protected $hidden = array('pivot.created_at');
}
@monove Following trick worked for me...
Add following method to your Model.
/**
* Convert the model instance to an array.
*
* @return array
*/
public function toArray()
{
$attributes = $this->attributesToArray();
$attributes = array_merge($attributes, $this->relationsToArray());
unset($attributes['pivot']['created_at']);
return $attributes;
}
@vatps yes!!! man thank you!!!
great!! thank you :)
You can also use that toArray()
function to rename your pivot value so it's "inline" with the rest of your data.
i.e.
public function toArray()
{
$attributes = $this->attributesToArray();
$attributes = array_merge($attributes, $this->relationsToArray());
// Detect if there is a pivot value and return that as the default value
if (isset($attributes['pivot']['value'])) {
$attributes['value'] = $attributes['pivot']['value'];
unset($attributes['pivot']);
}
return $attributes;
}
Mark, thank you guys
@taylorotwell Any way to remove using query builder? ie. I need pivot key in a specific endpoint.
Adding pivot
to $hidden
doesn't sound right. There are multiple contexts where pivot
property can appear, for different relationships and different use cases. I don't see much value in hiding it from "everywhere".
Adding
pivot
to$hidden
doesn't sound right. There are multiple contexts wherepivot
property can appear, for different relationships and different use cases. I don't see much value in hiding it from "everywhere".
you can temporarily hide attributes using makeHidden()
, documented since ~5.2
Most helpful comment
Add it to your "hidden" array.