How to Select Certain Fields in Laravel Eloquent?
79,080
Solution 1
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();
Solution 2
Selecting multiple columns
CategoryModel::get(['catName', 'catID', 'imgPath']);
Works with Laravel 5.3 too!
Solution 3
CategoryModel::wherecatType('Root')
->pluck('catName', 'catID', 'imgPath');
Solution 4
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');
Comments
-
rkaartikeyan over 4 years
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 )
-
cartbeforehorse over 6 yearsDoes anyone have a link to the documentation pages? I can't find them. Specifically, I'd like to better understand the
select()
function. -
otosturop over 4 yearsthanks also all() method works on both(string and array) laravel version 6.x
-
Haritsinh Gohil over 4 years@otosturop, thanks for suggestion, i have updated the answer for it.
-
Haritsinh Gohil over 4 years@otosturop, i have found out that
all
method callsget
method but takesarray
orstring
both as arguments sincelaravel version 5.1
, so fromlaravel 5.1
string
orarray
both will work inall()
method's argument.