Search code examples
laravelcontroller

Laravel. Get single column values of a table using Query Builder


I have a table named "items" and an input for the where condition named "ref_code".

$items = DB::table('items')
             ->where('ref_code','=', $request->ref_code)
             ->get(['id', 'ref_code', 'name','price']);

But I can't seem to take the values of each column.

I checked wether the query builder worked or not by using:

return $items;

Fortunately, there's no problem.

But returning or getting a single value doesn't work with:

return $items->id

Is my syntax wrong? All of this are inside my controller.

EDIT: I tried

dd($items);

before returning and it showed me this:

  Collection {#325 ▼
  #items: array:1 [▼
    0 => {#322 ▶}
  ]
}

Solution

  • Thanks for updating your question with the result. Look at your debug result. it looks like

    array:1 [▼
        0 => {#322 ▶}
      ]
    

    That means your query returning a collection of arrays because of you're using get() method. so get() method always return a collection of an array.

    For avoiding this problem you have to use first() method instead of get(). Remember: all the time you have to use first() method when you want to get a single row.

    So your query should be like :

    $items = DB::table('items')
                 ->select('id', 'ref_code', 'name', 'price')
                 ->where('ref_code','=', $request->ref_code)
                 ->first();
    

    Or

    $item = YourModelName::select('id', 'ref_code', 'name', 'price')
                 ->where('ref_code','=', $request->ref_code)
                 ->first();
    

    And finally get output as like $item->id, $item->ref_code etc.

    Hope it will help.

    References: https://laravel.com/docs/5.4/queries#retrieving-results