How to Do following Query in Laravel Eloquent?
SELECT catID, catName, imgPath FROM categories WHERE catType = \"Root\"
I have tried followi
CategoryModel::wherecatType('Root')
->pluck('catName', 'catID', 'imgPath');
Selecting multiple columns
CategoryModel::get(['catName', 'catID', 'imgPath']);
Works with Laravel 5.3 too!
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');
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();
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.