Howard
Howard

Reputation: 3758

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

Upvotes: 8

Views: 15741

Answers (2)

DukesNuz
DukesNuz

Reputation: 87

Here is another way, similar to @patricus.

$did = User::findOrFail($id, ['first_name', 'last_name']);

Upvotes: 1

patricus
patricus

Reputation: 62308

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

Upvotes: 15

Related Questions