phplaravellaravel-5

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

  • 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();