Alex
Alex

Reputation: 3855

Fetch the value of a given column in Eloquent

I am trying to get the value of a single column using Eloquent:

MyModel::where('field', 'foo')->get(['id']); // returns [{"id":1}]

MyModel::where('field', 'foo')->select('id')->first() // returns {"id":1}

However, I am getting anything but the value 1. How can get that 1?

NOTE: It is possible that the record with field of foo does not exist in the table!

EDIT

I am ideally looking for a single statement that either returns the value (e.g. 1) or fails with a '' or null or other. To give you some more context, this is actually used in Validator::make in one of the rules:

'input' => 'exists:table,some_field,id,' . my_query_above...

EDIT 2

Using Adiasz's answer, I found that MyModel::where('field', 'foo')->value('id') does exactly what I need: returns an integer value or an empty string (when failed).

Upvotes: 3

Views: 16651

Answers (4)

Paul Trimor
Paul Trimor

Reputation: 340

In PHP7:

MyModel::find($id)->{$value}

Upvotes: 1

Rehan Arshad
Rehan Arshad

Reputation: 490

In Laravel 8 with the help of Eloquent, you can use the following:

MyModel::find(PK)->getAttribute('name')
  • MyModel is the model name
  • PK is the primary-key (the row which you are looking for)
  • name is the column of which value you want to return

note: getAttribute() allows you to specify a single column whereas getAttributes() allows you to specify an array of columns.

Upvotes: 1

ollieread
ollieread

Reputation: 6133

You're using the Eloquent query builder, so by default, it'll return an Eloquent model with only the value you wish.

The method you're looking for is pluck() which exists in the normal query builder (of which the Eloquent one extends) so your code should look as follows:

MyModel::where('field', 'foo')->pluck('id'); // returns [1]

The value() method that is being used in the other answers is an Eloquent model method. Using that means that the framework queries the database, hydrates the model and then returns only that value. You can save yourself a few keystrokes and few CPU cycles by using pluck() and have it handled simply in one query.

Upvotes: 6

Adiasz
Adiasz

Reputation: 1804

Laravel is intuitive framework... if you want value just call value() method.

MyModel::find(PK)->value('id');

MyModel::where('field', 'foo')->first()->value('id');

Upvotes: 8

Related Questions