Anon Anon - 1 year ago 84
PHP Question

Cannot retirieve single column from database. Laravel

I'm trying to retrieve single column from my table grades.
For that I have used following code in my controller:

public function verify($id,$sid)

return $grade;


Where, annual is column name. But it is returning empty set of array [].
Can anyone help me?

Answer Source

all() takes a list of columns to load from the database. In your case, you're fetching only one column called annual, therefore filtering on id later on does not return results. Replace your code with the following and it should work:

$grade = Grade::all('id', 'annual')->whereLoose('id', $id);

Keep in mind that it will return a collection of objects, not a single object.

NOTE: you're always loading all Grade objects from the database which is not efficient and not necessary. You can simply fetch object with given id with the following code:

$grade = Grade::find($id); // fetch all columns
$grade = Grade::find($id, ['id', 'annual']); // fetch only selected columns
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download