PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 11, 2022

[FIXED] Laravel pluck but combining first name + last name for select

 March 11, 2022     eloquent, jquery-select2, laravel, laravel-5     No comments   

Issue

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?


Solution

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()
    {
       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('full_name', 'id')

$customers = Customer::all()->pluck('full_name', 'id');
  • 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.

Updated Date:- 26th Aug, 2021 If we use computed Attribute accessor functionality, then mind it one important thing...

Laravel Accessor functionality works after the Data fetched from DataBase. So we have to declare "pluck(accessorName)" at the end of Query....

For Example:-

Wrong Methods:-

$data = Model::pluck('full_name','id)->get(); 
$data = Model::pluck('full_name','id)->all();

in above two queries if you does not have full_name field in DataTable you will get Unknown column error

Right Methods:-

$data = Model::get()->pluck('full_name','id');
$data = Model::all()->pluck('full_name','id');

in above two queries it will works perfectly even if you doesn't have full_name field in DataTable



Answered By - dev7
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing