Home > Blockchain >  Laravel find by primary key and return a single column value
Laravel find by primary key and return a single column value

Time:06-19

I am trying to do a search and return a single value. I am getting different results depending on how I try to get the value.

If the table has the following values:

id name
1 Professional I
2 Professional II
3 Professional III
4 Professional IV
5 Teacher I
6 Teacher II

And I set $type = 4, I expect to get Professional IV. CertificateRequest::find($type)->name; Returns Professional VI which is what I want.

However,

CertificateRequest::find($type)->value("name"));

and

CertificateRequest::find($type)->first()->value("name"); Both return Professional I

What am I doing wrong? The problem with the first approach is if $type = null, I get Attempt to read property "name" on null. It also becomes harder to dynamically pass a column name.

CodePudding user response:

Use


CertificateRequest::findOrFail($type)->name; 

Will return data or 404, not null.

CodePudding user response:

You can try

$data = CertificateRequest::where('id',$type)->get();

CodePudding user response:

This code should do what you want:

CertificateRequest::where('id', $type)->value("name"));

The difference is that find executes the query, which means that value seems to execute a second query without the type parameter. The where method modifies the query without executing it, allowing the value method to execute the query and return a result.

  • Related