Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Select Certain Fields in Laravel Eloquent?

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 )
like image 460
rkaartikeyan Avatar asked Feb 15 '15 19:02

rkaartikeyan


People also ask

How can I get specific field in Laravel?

Select specific columns with Laravel Eloquent To get all of the columns from the users table, we would use the following: $user = User::where('username', 'bobbyiliev')->get(); However, if you wanted to get only a specific column, you could pass it as an argument to the get() method.

What is difference between Pluck and select in Laravel?

Pluck function normally used to pull a single column from the collection or with 2 columns as key, value pairs, which is always be a single dimension array. Select will return all of the columns you specified for an entity in a 2 dimensional array, like array of selected values in an array.

What is subquery in Laravel?

Subqueries allow you to run nested queries within another database query. This can be a powerful way to retrieve ancillary model data, without making any additional database queries, when it's not possible to do via a relationship.

What is advantage of eloquent in Laravel?

Eloquent is an ORM, which means can automatically handle the relationships of your models for you. You can retrieve related models without writing complex queries. You can even retrieve database information without any kind of database knowledge at all.


2 Answers

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();
like image 147
lukasgeiter Avatar answered Sep 29 '22 18:09

lukasgeiter


Selecting multiple columns

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

Works with Laravel 5.3 too!

like image 26
Harry Bosh Avatar answered Sep 29 '22 17:09

Harry Bosh