Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select specific columns using find in Eloquent ORM

In Laravel how can I get specific columns using find? I know you can do it with get like this:

$user = User::where('u_id', '=', 1)
        ->get(['firstname', 'lastname']);

Is there a way to do it with find? This is what I currently have:

$user = User::find(1);
like image 259
rotaercz Avatar asked Jan 18 '16 10:01

rotaercz


People also ask

How do I select a specific column 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 the difference between query builder and eloquent ORM?

Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.

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.

Is eloquent an ORM?

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.


2 Answers

You have two options.

First, you can pass the columns to select as the second parameter to find():

$user = User::find(1, ['firstname', 'lastname']);

Second, although somewhat specialized, find() is just the method used to execute the query, so you can modify the query as normal beforehand (add selects, wheres, orders, etc.). Therefore, you can just add a select() before you execute the find():

$user = User::select(['firstname', 'lastname'])->find(1);
like image 119
patricus Avatar answered Sep 22 '22 17:09

patricus


Here is another way, similar to @patricus.

$did = User::findOrFail($id, ['first_name', 'last_name']);
like image 34
DukesNuz Avatar answered Sep 22 '22 17:09

DukesNuz