Skip to content
Advertisement

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"}]

Advertisement

Answer

Edit:

Sorry i forgot about pluck() as many have commented : Easiest way is :

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

Which will directly return the only the first result for the requested row as a string.

Using the fluent query builder you will obtain an array anyway. I mean The Query Builder has no idea how many rows will come back from that query. Here is what you can do to do it a bit cleaner

$result = DB::table('users')->select('groupName')->where('username', $username)->first();

The first() tells the queryBuilder to return only one row so no array, so you can do :

return $result->groupName;

Hope it helps

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement