Search code examples
laravellaravel-5laravel-5.4laravel-collection

How to except some element from collection Laravel?


I do request to Model:

$user = User::findOrFail($id)->get();

And afetr try to except some fields from $user collection:

$user = $user->except(['surname', 'is_buyer', 'password']);

But in result I get still full $user collection


Solution

  • The problem here is that you don't have here collection as you expect. You have here collection of models, so you will get all model fields. Also using:

    $user = User::findOrFail($id)->get();
    

    is really strange, as you will get always 1 record and put this into collection.

    Depending on your needs you might want to choose only some fields from database like this:

    $user = User::select('id', 'name')->findOrFail($id);
    

    instead of using collections here.