Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 287
Yahya Uddin Avatar asked Aug 19 '17 23:08

Yahya Uddin


People also ask

How do you unset a value in Laravel?

We use forget() method for unset/delete an item from laravel collection by its key.

What does eloquent delete return?

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 .

How do I unset a key in Laravel?

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.


1 Answers

You can use

$model->offsetUnset('propertyName');
like image 129
Кляченков Геннадий Avatar answered Sep 24 '22 06:09

Кляченков Геннадий