How to Select Certain Fields in Laravel Eloquent?

If you want to get certain columns then You can use one of the two method get() or all()

but the syntax is different for both, get() method takes array as argument and all() method takes string or array both as argument:

Model::all('field1','field2') with string as arguments

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

Model::all(['field1','field2']) with array as arguments

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

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

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

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

Selecting multiple columns

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

Works with Laravel 5.3 too!


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();