Laravel how to return single column value using Query Builder

laravel, php

Solution

EDIT: As of version 5.1 `pluck` is deprecated, since 5.2 its meaning is completely different (as `lists` used to be), so use `value` method instead.

You're trying to get property of the array, so obviously you're getting error.

If you need single field only, then use `pluck` (which returns single value - string by default):

// let's assume user_id is 5

DB::table('attendances')
  ->where('date_only', '=', $newdate)
  ->orderBy('logon','asc')
  ->pluck('user_id');  // "5"

When you need whole row, then `first` (which returns stdObject):

$att = DB::table('attendances')
  ->where('date_only', '=', $newdate)
  ->orderBy('logon','asc')
  ->first();

$att->user_id; // "5"
$att->any_other_column;

And `get` is when you want multiple results (which returns simple array of stdObjects):

$result = DB::table('attendances')
  ->where('date_only', '=', $newdate)
  ->orderBy('logon','asc')
  ->get();

$result; // array(0 => stdObject {..}, 1 => stdObject {..}, ...)
$result[0]->user_id; // "5"

Problem

I want to use the data from the SQL Query, to explain it further here is my code: ``` $myquery = DB::table('attendances')->select('user_id')->where('date_only', '=', $newdate)->orderBy('logon','asc')->get(); $myquery->user_id; ``` Now I want the value of my $myquery to be USER_ID's value, I get error if I used the Above code -$myquery->user_id;

Original source