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?
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:
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 useCustomer::all()->pluck('id', 'full_name')
Customer::all(['id', 'first_name', 'last_name'])->pluck(...)
so that we don't pull unnecessary columns from the db.Hope this helps.
You can do it like this,
or you also do like this,
or with PHP way,
For me it worked