Reputation: 4165
I want to get a single value from 1 record in the DB but have an error...
$gamer_name = Gamer::where('user_id', $gamer_id)->first()->name;
As a result, I have this...
Trying to get property of non-object
If I remove ->name
from the request like this
$gamer_name = Gamer::where('user_id', $gamer_id)->first();
then I get App\Gamer Object
data instead of a name. I can't just get the single value from a single row with Eloquent.
Upvotes: 0
Views: 97
Reputation: 604
there are various solution for this query and on of the easiest may be
$gamer_name = Gamer::where('user_id', $gamer_id)->first()->select('name');
next one
$gamer_name = Gamer::where('user_id', $gamer_id)->first()->value('name');
Upvotes: 0
Reputation: 2453
You can use pluck()
for that purpose
$gamer_name = Gamer::where('user_id', $gamer_id)->pluck('name');
Documentation : https://laravel.com/docs/4.2/queries#selects
Upvotes: 1
Reputation: 42694
Using a query builder instead of a collection, but it should work:
$gamer_name = DB::table("gamers")->where("user_id", $gamer_id)->value("name");
If you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:
$email = DB::table('users')->where('name', 'John')->value('email');
Upvotes: 0