Search code examples
databaselaravellaravel-query-builderlaravel-6

unexpected result in a query in laravel


I’m a beginner in Laravel but have a problem at first. I wrote this query and I’m waiting for Sonya Bins as result but unexpectedly I see ["Sonya Bins"]. what’s the problem?

Route::get('products', function () {
$articles=DB::table('users')->where('id','2')->get()->pluck('name');
return view('products',compact('articles'));
});

Solution

  • pluck will return array if you want to get only single value then use value

    // will return array
    $articles=DB::table('users')->where('id','2')->get()->pluck('name');
    
    //will return string
    $articles=DB::table('users')->where('id','2')->value('name');
    // output Sonya Bins
    

    here is an example from the documentation:

    if you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:

    $email = DB::table('users')->where('name', 'John')->value('email');
    

    Read more about it here Hope it helps.

    Thanks