Laravel pluck but combining first name + last name for select

时光怂恿深爱的人放手 提交于 2019-12-13 15:18:18

问题


Using select2 with a Laravel / Vue project and need to return JSON in the following format:

[
    { id: 0, text: 'enhancement' },
    { id: 1, text: 'bug' }
]

In Laravel I know I can use pluck to create my list data e.g. for customers:

$customers = Customer::pluck('id', 'first_name');

But Want to return the id and first name + last name as a single name.

How can I do this?


回答1:


Have you tried using Accessors?

https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor

I have not tested it but this could work:

add this to your Customer Eloquent Model:

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

and then try:

UPDATED pluck on accessor will only work on a collection. If you try Customer::pluck('id', 'full_name') it will not work since there is no db column named full_name, therefore you must use Customer::all()->pluck('id', 'full_name')

$customers = Customer::all()->pluck('id', 'full_name');
  • as a side note, for performance it is probably better to do Customer::all(['id', 'first_name', 'last_name'])->pluck(...) so that we don't pull unnecessary columns from the db.

Hope this helps.




回答2:


You can do it like this,

$customers = DB::table('customers')->select("id", "CONCAT(firstname,' ',lastname) as fullname")->get();

or you also do like this,

$customers = DB::table('customers')->select(DB::raw('CONCAT(firstname,' ',lastname) as fullname, id'))->get();

or with PHP way,

$fullname = $customers->firstname. " " .$customers->lastname;



回答3:


For me it worked

\DB::table("admin as c")->select(\DB::raw("CONCAT(FirstName, ' ', LastName) AS FIRSTNAME"),"c.AdminID")->pluck("FIRSTNAME","AdminID");


来源:https://stackoverflow.com/questions/44475537/laravel-pluck-but-combining-first-name-last-name-for-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!