19

I'm trying to retrieve data from database and bind them to a html select tag, and to bind them i need to use pluck so i get the field i want to show in a array(key => value), because of FORM::select. The normal pluck gets all the results, while i want to use distinct. My model is Room and it looks like:

    class Room extends Eloquent
{
    public $timestamps = false;

    protected $casts = [
        'price' => 'float',
        'floor' => 'int',
        'size' => 'float'
    ];

    protected $fillable = [
        'capacity',
        'description',
        'price',
        'floor',
        'size',
        'type',
        'photo_name'
    ];
}

While my function I'm using in the controller look like:

public function getRooms()
    {
        $roomType = Room::pluck('type','type');
        $roomFloor = Room::pluck('floor','floor');

        return view('roomgrid')->with('type',$roomType)->with('floor',$roomFloor);
    }

And my view contains this piece of code to get floors:

{{FORM::select('floor', $floor, null,['class'=>'basic'])}}

Like this i get duplicated floors, that i don't want. Is there any way so i can get distinct floors and pluck them? Thanks in advance.

Arlind Hajdari
  • 385
  • 1
  • 3
  • 12

4 Answers4

25

Why not use groupBy()?

$roomType = Room::groupBy('type')->pluck('type','type');
Buglinjo
  • 1,822
  • 1
  • 13
  • 24
  • I was using this backwards and it wasn't working xd. It worked, thanks for the fast answer. – Arlind Hajdari Feb 24 '17 at 20:33
  • Yeah backwards it will not work because pluck get's array not Collection object. If you had ->get() instead of pluck() it will get Collection object but groupBy will create nested array. So you only need to use eloquent to simply call MYSQL GROUP BY query and that's it. – Buglinjo Feb 24 '17 at 20:35
  • 1
    I am just curious, why you have given two parameters to pluck ? Cant it be: `Room::groupBy('type')->pluck('type');` ? – Learner Apr 24 '18 at 13:43
  • 1
    @Learner He needed key and value to be the same as I understood from his examples. – Buglinjo Apr 24 '18 at 19:35
  • in terms of performance - this is the best eloquent solution? – Dr. House Sep 18 '18 at 10:00
16
Room::unique('floor')->pluck('floor', 'floor');
iateadonut
  • 1,241
  • 11
  • 22
5

distinct can do the trick:

Room::query()->distinct()->pluck('type');

Which will be translated into the following SQL:

SELECT DISTINCT type FROM rooms
vbarbarosh
  • 2,946
  • 3
  • 26
  • 40
3

2019 Update

You don't need to use 2 arguments with pluck()

simply do:

$roomType = Room::groupBy('type')->pluck('type');

of course for getting it into array:

$roomType = Room::groupBy('type')->pluck('type')->toArray();

Sometimes I use the result for whereIn clause, its useful for that.

Community
  • 1
  • 1
Learner
  • 9,004
  • 6
  • 35
  • 55