Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: getting a single value from a MySQL query

I'm trying get a single value from MySQL database using laravel but the problem I'm getting an array . this is my query result in MySQL command line:

select groupName from users; 

+-----------+ | groupName | +-----------+ | Admin     | +-----------+ 

my laravel function:

public static function PermitAddNewUser(){     $username=Session::get('key');     $data=DB::select("select groupName from users where username='$username';");     return $data;  } 

expected $data value is a string with value= Admin

but what i get is : [{"groupName":"Admin"}]

like image 824
Osama Al-Banna Avatar asked Sep 19 '14 09:09

Osama Al-Banna


People also ask

What is pluck in Laravel?

Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.

How can get data from database 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.


1 Answers

yet another edit: As of version 5.2 pluck is not deprecated anymore, it just got new behaviour (same as lists previously - see side-note below):

edit: As of version 5.1 pluck is deprecated, so start using value instead:

DB::table('users')->where('username', $username)->value('groupName');     

// valid for L4 / L5.0 only DB::table('users')->where('username', $username)->pluck('groupName'); 

this will return single value of groupName field of the first row found.


SIDE NOTE reg. @TomasButeler comment: As Laravel doesn't follow sensible versioning, there are sometimes cases like this. At the time of writing this answer we had pluck method to get SINGLE value from the query (Laravel 4.* & 5.0).

Then, with L5.1 pluck got deprecated and, instead, we got value method to replace it.

But to make it funny, pluck in fact was never gone. Instead it just got completely new behaviour and... deprecated lists method.. (L5.2) - that was caused by the inconsistency between Query Builder and Collection methods (in 5.1 pluck worked differently on the collection and query, that's the reason).

like image 103
Jarek Tkaczyk Avatar answered Sep 25 '22 15:09

Jarek Tkaczyk