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');
Share:
79,080
rkaartikeyan
Author by

rkaartikeyan

I am a Website Developer using Both PHP and ASP.

Updated on January 15, 2020

Comments

  • rkaartikeyan
    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
    cartbeforehorse over 6 years
    Does anyone have a link to the documentation pages? I can't find them. Specifically, I'd like to better understand the select() function.
  • otosturop
    otosturop over 4 years
    thanks also all() method works on both(string and array) laravel version 6.x
  • Haritsinh Gohil
    Haritsinh Gohil over 4 years
    @otosturop, thanks for suggestion, i have updated the answer for it.
  • Haritsinh Gohil
    Haritsinh Gohil over 4 years
    @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.