20

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 )
1
  • 2
    Surely CategoryModel::select('catName', 'catID', 'imgPath')->where('catType', '=', 'Root')->get() would be better?
    – Mark Baker
    Commented Feb 15, 2015 at 19:53

5 Answers 5

48

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

Selecting multiple columns

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

Works with Laravel 5.3 too!

5

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');
3
  • 1
    thanks also all() method works on both(string and array) laravel version 6.x
    – otosturop
    Commented Jan 14, 2020 at 11:23
  • @otosturop, thanks for suggestion, i have updated the answer for it. Commented Jan 15, 2020 at 6:01
  • @otosturop, i have found out that all method calls get method but takes array or string both as arguments since laravel version 5.1, so from laravel 5.1 string or array both will work in all() method's argument. Commented Jan 15, 2020 at 6:13
4
CategoryModel::wherecatType('Root')
            ->pluck('catName', 'catID', 'imgPath');
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.