Reputation: 31
I am a beginner of using Laravel, in this case i am going to get a data(price) from database and then define it as an variables($price) for further process.
The problem is when i define the variables $price and try to echo it to test the out come, it occurred a error called "Object of class stdClass could not be converted to string".
I try to figure out the problems these day, realize that there are something wrong on the result from the database. It changes to an Object of class stdClass instead of an array? However, when i use all the solution that i found on the internet it still doesn't work........
Solution i have already tried:
$array = json_decode(json_encode($price), true);
$price = array();
->toArray(); //Used in my code
Below are my Controller.blade.php
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Menu $menu
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $day)
{
$opt1 = $request->post('dishopt1');
$price1 = DB::table('dishes')->select('price', 'chg_porridge')->where([
['name', '=', $opt1],
])->get()->toArray();
$price1 = $price1[0];
echo $price1;
}
Upvotes: 1
Views: 9469
Reputation: 7334
DB::table()->get()
returns a collection of StdClass
(see: What is stdClass in PHP?) object and that is why you have an object as result when you picked the first one (See: Laravel Query Builder - Retrieving Result).
Well this is intended by Laravel. Its either you simply cast the response with (array)$price1
or you use ->json()
method of Illuminate\Contracts\Routing\ResponseFactory
interface which makes your return like this:
return response()->json($price1);
NB:
get()
then convert to array and retrieve the first item, you can simply do ->first()
instead of get()
then you have the first StdClass
object.echo
. Laravel would do the magic for you.dd()
- dump and die or dump()
Upvotes: 0
Reputation: 154
$price1 = DB::table('dishes')->select('price', 'chg_porridge')->where([
['name', '=', $opt1],
])->get();
$values = json_decode(json_encode($price1), true);
Upvotes: 1
Reputation: 17216
You can avoid doing all that by using the method value()
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Menu $menu
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $day)
{
$opt1 = $request->post('dishopt1');
$price1 = DB::table('dishes')->where([
['name', '=', $opt1],
])->value('price');
echo $price1;
}
Upvotes: 0