Search code examples
phplaraveleloquent

Laravel find by primary key and return a single column value


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.


Solution

  • 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.