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 ▶}
]
}
If you want to get single row and from the that row single column, one line code to get the value of the specific column is to use find() method alongside specifying of the column that you want to retrieve it.
you can easily use it with laravel 6 and laravel 7 application. take() will help to get data from a database table with a limit. skip() will help to skip some records when you fetch data from the database table.
Think of it like this: when you don't exactly know what a query will return then you need to use get() . For example you can't use it with all() since you know that it will return all the records and no further conditions can be applied. It's the same with find() since you know it will only try to fetch one record.
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
get()
would return a collection
$items = DB::table('items')
->where('ref_code','=', $request->ref_code)
->get(['id', 'ref_code', 'name','price']);
In the above case $items
would be a collection, hence you need to loop through the collection to access the properties
foreach ($items as $item) {
$item->price;
}
If you'd need to return a Model instance you could use the method first()
instead
$items = DB::table('items')
->select('id', 'ref_code', 'name', 'price')
->where('ref_code','=', $request->ref_code)
->first();
and access the properties as
$items->price;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With