Laravel ::pluck multiple columns

前端 未结 5 1121
清歌不尽
清歌不尽 2021-02-18 18:54

I need to populate a blade format

提交评论

  • 2021-02-18 19:22

    Another simple way:

        return User::select(DB::raw('CONCAT(first_name, " - ", last_name) AS full_name, id'))
               ->pluck('full_name', 'id');
    
    0 讨论(0)
  • 2021-02-18 19:30

    Just so people who come here know, the pluck method returns an object, and if you want to pluck multiple columns and return an array at the same time without using the toArray method, you could just pass the names of the column to the all() function, and it will return the wanted columns as an array.

    YourModelName::all('id', 'name');
    
    0 讨论(0)
  • 2021-02-18 19:45

    Best solution is to create accessor function into your model, let's assume if you want to get full name then you can do like this.

    public function getFullNameAttribute()
    {
        return $this->first_name . ' ' . $this->last_name;
    }
    

    and you can easily get full name.

    $users = User::where('id', 1)->get()->pluck('full_name', 'id');
    

    Eloquent will call getFullNameAttribute function and get concatenated value.

    0 讨论(0)
  • 2021-02-18 19:46

    Model results retrieved by the get() method are just children of the regular Support-Collection class, so you actually get access to all the same goodies. Try this:

    $eloquentCollection = app(YourModel::class)
        ->where('field', 'value')
        ->get(['id', 'column_1', 'column_2']);
    
    $mapped = $eloquentCollection->mapWithKeys(function (YourModel $model) {
        return [$model->id => $model->column_1 . $model->column_2];
    })
    
    0 讨论(0)
  • 提交回复
    热议问题