How to exclude certains columns while using eloquent

前端 未结 8 1265
梦谈多话
梦谈多话 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:34

    using hidden array in model is good, but if you don't want to hide your column all the time and use makeVisible to access them in need, then instead, hide your column from serialization where you need with makeHidden function like this :

    $res = Model::where('your query')->get();
    $res->makeHidden(['column_one','column_two','column_n']);
    return response()->json($res);
    
    0 讨论(0)
  • 2020-12-02 22:34

    You can use unset unset($category->created_at,$category->updated_at);

    $fcategory = array();
    $kCategory = KCategory::where("enabled", true)->get();
    foreach ($kCategory as $category) {
        $subkCategory = PostCategory::select("id", "name", "desc")
            ->where("id_kcategory", $category->id)
            ->where("enabled", true)
            ->get();
    
        unset($category->created_at, $category->updated_at);
    
        $fcategory[] = $category;
    }
    
    0 讨论(0)
  • 2020-12-02 22:37

    If you only need to hide attributes from your model's array or JSON representation, you may add the $hidden property to your model or use the makeHidden function, see other answers for more details. But sometimes you don't want to load huge data (geospatial, html, logs...) into your application, it will be slow and take more memory. OP asked for an SQL query hence my answer, but most of the time it's more convenient to only hide the data from the JSON response.


    AFAIK there is no build in option in SQL to exclude columns explicitly, so Laravel can't do it. But you can try this trick

    Update

    Another trick is to specify all columns in your model and add a local scope function

    protected $columns = ['id','pseudo','email']; // add all columns from you table
    
    public function scopeExclude($query, $value = []) 
    {
        return $query->select(array_diff($this->columns, (array) $value));
    }
    

    Then you can do :

    $users = User::where('gender', 'M')
        ->where('is_active', 1)
        ->exclude(['pseudo', 'email', 'age', 'created_at'])
        ->toArray();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-02 22:39

    I don't know about previous Laravel version, but in 5.4 you can put this line in User model

    protected $hidden = ['pseudo', 'email', 'age', 'created_at'];
    

    and then User::find(1); will return all fields except pseudo, email, age, and created_at.

    But you still can retrieve those hidden fields by using:

    $user = User::find(1);
    $email = $user['email']; // or $user->email;
    
    0 讨论(0)
  • 2020-12-02 22:43

    I have looked into the answer by @Razor

    But there is Very Conveinent way by skipping $columns property

    /**
         * Scope a query to only exclude specific Columns
         *
         * @param  \Illuminate\Database\Eloquent\Builder $query
         * @return \Illuminate\Database\Eloquent\Builder
         */
        public function scopeExclude($query, ...$columns) 
        {
            return $query->select( array_diff( $this->getTableColumns(),$columns) );
        }
    
        /**
         * Shows All the columns of the Corresponding Table of Model
         *
         * @author Manojkiran.A <manojkiran10031998@gmail.com>
         * If You need to get all the Columns of the Model Table.
         * Useful while including the columns in search
         * @return array
         **/
        public function getTableColumns()
        {
            return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
        }
    

    getTableColumns function will get all the columns of the table so you dont need to define the

    $column property

    0 讨论(0)
提交回复
热议问题