Home » Php » How to Select Certain Fields in Laravel Eloquent?

How to Select Certain Fields in Laravel Eloquent?

Posted by: admin November 29, 2017 Leave a comment

Questions:

How to Do following Query in Laravel Eloquent?

SELECT catID, catName, imgPath FROM categories WHERE catType = "Root"

I have tried following

CategoryModel::where('catType', '=', 'Root')
                ->lists('catName', 'catID', 'imgPath');

but its return only two fields.

Array ( [7] => Category 1 )
Answers:

lists() turns the resulting collection into an array with key value. You can only have two database columns in there. Otherwise you have to use select() but then you will get a collection of models not just an array.

$categories = CategoryModel::select('catID', 'catName', 'imgPath')
                           ->where('catType', '=', 'Root')
                           ->get();

Questions:
Answers:
CategoryModel::wherecatType('Root')
            ->pluck('catName', 'catID', 'imgPath');

Questions:
Answers:

Selecting multiple columns

CategoryModel::get(['catName', 'catID', 'imgPath']);

Works with Laravel 5.3 too!

Questions:
Answers:

From laravel version 5.3^ lists() is deprecated and function pluck() is used instead.

pluck() returns a collection and if you need a simple array just prepend ->toArray() to it.