Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pluck with multiple columns?

When i use pluck with multiple columns i get this:

{"Kreis 1 \/ Altstadt":"City","Kreis 2":"Enge","Kreis 3":"Sihifeld","Kreis 4":"Hard","Kreis 5 \/ Industriequartier":"Escher Wyss","Kreis 6":"Oberstrass","Kreis 7":"Witikon","Kreis 8 \/ Reisbach":"Weinegg","Kreis 9":"Altstetten","Kreis 10":"Wipkingen","Kreis 11":"Seebach","Kreis 12 \/ Schwamendingen":"Hirzenbach"

But i need this?

["Rathaus","Hochschulen","Lindenhof","City","Wollishofen","Leimbach","Enge","Alt-Wiedikon","Friesenberg","Sihifeld","Werd","Langstrasse","Hard","Gewerbechule","Escher Wyss","Unterstrass","Oberstrass","Fluntern","Hottingen","Hirslanden","Witikon","Seefeld","M\u00fchlebach","Weinegg","Albisrieden","Altstetten","H\u00f6ngg","Wipkingen","Affoltern","Oerlikon","Seebach","Saatlen","Schwamendingen-Mitte","Hirzenbach"]

Any suggestion how can i do that? This is my method:

    public function autocomplete_districts(Request $request)
   {
      $district = $request->input('query');
      // $ass = /DB::table('districts')->select(array('district', 'region'))->get();
      // dd($ass);
      $data = Districts::whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->pluck('region','district');

      return response()->json($data);
   }
like image 238
None Avatar asked Mar 22 '17 09:03

None


3 Answers

You should use select() with get() and then later on modify the object as you need.

So instead of: ->pluck('region','district'); use: ->select('region','district')->get();

pluck() is advised when you need value of one column only.

And as far as possible, you should have your models singular form not plural (Districts) - to follow Laravel nomenclature.

like image 72
Abhay Maurya Avatar answered Oct 18 '22 01:10

Abhay Maurya


Cos that is how pluck works. Instead try this.

$data = Districts::whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->select('region', 'district')->get();

$data = collect($data->toArray())->flatten()->all();
like image 34
Saravanan Sampathkumar Avatar answered Oct 18 '22 01:10

Saravanan Sampathkumar


In my case I wanted to pluck 2 values from an array of Eloquent models and this worked:

$models->map->only(['state', 'note'])->values()

That's shorter version of

$models->map(fn($model) => $model->only(['state', 'note']))->values()
like image 41
Orkhan Alikhanov Avatar answered Oct 18 '22 02:10

Orkhan Alikhanov