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?
We use forget() method for unset/delete an item from laravel collection by its key.
Laravel Eloquent provides destroy() function in which returns boolean value. So if a record exists on the database and deleted you'll get true otherwise false .
you can remove key from array in laravel 6, laravel 7, laravel 8 and laravel 9 by array helper. But if you work on laravel then you can array helper function. we can remove multiple key from variable using array_except() of Laravel pre-define function.
You can use
$model->offsetUnset('propertyName');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With