How to exclude certains columns while using eloquent

前端 未结 8 1274
梦谈多话
梦谈多话 2020-12-02 21:59

When I\'m using eloquent, I can use the \"where\" method then the method \'get\' to fill an object containing what I\'ve selected in my database. I mean:

$us         


        
8条回答
  •  北海茫月
    2020-12-02 22:37

    We get the object eloquent from the model full with all fields, transform it to array and we put it inside of a collection. Than we get all fields except all fields specified in array $fields.

    $fields = ['a', 'b', 'c', 'N'];
    $object = Model::find($id);
    return collect($object->toArray())->except($fields);
    

    More clearly, let's give an example:

    // Array of fields you want to remove
    $fields_to_remove = ['age', 'birthday', 'address'];
    
    // Get the result of database
    $user = User::find($id);
    
    // Transform user object to array
    $user = $user->toArray();
    
    // Create a collection with the user inside
    $collection = collect($user);
    
    // Get all fields of our collection except these fields we don't want
    $result = $collection->except($fields_to_remove);
    
    // Return
    return $result;
    

    This example above makes exactly the same thing of the first one, but it's more explained.

提交回复
热议问题