How to select specific fields in Laravel Rloquent?

How to make the following query in Laravel Rloquent?

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

I tried to follow

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

but returns only two fields.

Array ( [7] => Category 1 )
+6
source share
5 answers

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

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

Select multiple columns

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

Works with Laravel 5.3 too!

+2
source
CategoryModel::wherecatType('Root')
            ->pluck('catName', 'catID', 'imgPath');
+1

laravel 5.3 ^ lists() , pluck().

pluck() , , ->toArray() .

0

, get() all()

, get() array , all() string :

:: ( 'field1', 'field2')

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

:: ([ 'field1', 'field2'])

CategoryModel::get(['catName', 'catID', 'imgPath'])->where('catType','Root');
0

All Articles