'Laravel: Remove an attribute in returned result
I have the following code:
$orders = Order::all();
return $orders;
This returns something like this:
[
{
"id": 123,
"qr_code": "foo.png",
"qr_code_url": "http://example.com/foo.png"
},
{
"id": 112,
"qr_code": "bar.png",
"qr_code_url": "http://example.com/var.png"
}
]
Note that qr_code_url
is an appended attribute, and not an attribute stored in the database.
I want to return this collection back to the user without the attribute: qr_code
, in this case. So like this:
[
{
"id": 123,
"qr_code_url": "http://example.com/foo.png"
},
{
"id": 112,
"qr_code_url": "http://example.com/var.png"
}
]
Looking at the collection functions, i can't seem to find an easy way to do this: https://laravel.com/docs/5.4/collections
The only functions I have found close to what I want is: except
and forget
, but they seem to just work on a 1 dimension array. Not a collection result returned by a model.
How can I solve my problem?
Solution 1:[1]
You can set your attribute as hidden on the model class (see Hidding Attributes From Json)
/**
* The attributes that should be hidden for serialization.
*
* @var array
*/
protected $hidden = ['qr_code'];
The attribute will still be loaded, but it won't be shown in your collections.
If you don't want to make it permanent, you can use the makeHidden()
eloquent method as described on the docs:
Temporarily Modifying Attribute Visibility
If you would like to make some typically hidden attributes visible on a given model instance, you may use the makeVisible method. The makeVisible method returns the model instance for convenient method chaining:
return $user->makeVisible('attribute')->toArray();
Likewise, if you would like to make some typically visible attributes hidden on a given model instance, you may use the makeHidden method.
return $user->makeHidden('attribute')->toArray();
Solution 2:[2]
$eloquentCollection->transform(function (Model $result) use ($forgetThisKey) {
$attributes = $result->getAttributes();
unset($attributes[$forgetThisKey]);
$result->setRawAttributes($attributes, true);
return $result;
});
Solution 3:[3]
You can use
$model->offsetUnset('propertyName');
Solution 4:[4]
When you build api the recommended way of controlling output data is to use fractal transformers.
If it's to much and you want to keep it simple you can use laravel pluck
method on collections.
Solution 5:[5]
have had experience with this too. I've found a good solution here.
But, if you like a one-liner solution, you can also use the ff methods of Eloquent's Model class:
setHidden(array $hidden)
Ex: $user->setHidden(['name'])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | kmuenkel |
Solution 3 | ????????? ???????? |
Solution 4 | Mirceac21 |
Solution 5 | Uhelliton |