Search code examples
phplaravellaravel-query-builder

Getting specific column from sql database using raw query in laravel


I have this raw query that extracts data from the database table in Laravel

 $username = DB::table('hotspot_users')
 ->select('userName')  
 ->where('assignedTo', '786')->get();

I get these values: [{"userName":"kim"}]

but I want to extract just the username "kim" itself, not an array. I have tried to do this without success:

 $convert1=json_decode($username);
 $newusername=$convert1->userName; 

but i get an error: Trying to get property 'userName' of non-object

Any idea how I can solve this


Solution

  • You are getting the result of DB as php stdClass object, so you can iterate over it and get every variable that is queried. Something like below code may help you.

    In case of using get()

    $data = DB::table('hotspot_users')
               ->where('assignedTo', '786')->select('userName')->get();
    
    foreach ($data as $datum) {
        $result[] = $datum->userName;
    }
    

    In case of using first()

    $data = DB::table('hotspot_users')
                ->where('assignedTo', '786')->select('userName')->first()->userName;