Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel how to return single column value using Query Builder

Tags:

php

laravel

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;

like image 418
user3349495 Avatar asked Nov 26 '14 08:11

user3349495


People also ask

What is truncate () Laravel?

From the Laravel Docs https://laravel.com/docs/5.6/queries#deletes says: If you wish to truncate the entire table, which will remove all rows and reset the auto-incrementing ID to zero, you may use the truncate method: DB::table('users')->truncate();

How does Laravel query builder work?

In Laravel the database query builder provides an easy interface to create and run database queries. It can be used to perform all the database operations in your application, from basic DB Connection, CRUD, Aggregates, etc. and it works on all supported database systems like a champ.

How can we get data from database in controller in Laravel?

After configuring the database, we can retrieve the records using the DB facade with select method. The syntax of select method is as shown in the following table. Run a select statement against the database.


2 Answers

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" 
like image 67
Jarek Tkaczyk Avatar answered Sep 27 '22 16:09

Jarek Tkaczyk


That's for Laravel 5.3:

$user_id = DB::table('attendances')->select('user_id')->where('date_only', '=', $newdate)->orderBy('logon','asc')->value('user_id'); 
like image 30
Слаффка Островский Avatar answered Sep 27 '22 18:09

Слаффка Островский