I have some problems with showing json from controller to view. If I return only json response I have.
{"result":true,"title":"Cable"}
As normal.
But when I try to implement it to blade it's not working. I'm doing it like this in controller.
$data1 = $getProduct->index();
$data = array(
'title'=> $data1['title'],
'Description'=>'This is New Application',
);
and this in view
{{ $title }}
and error like
Cannot use object of type Illuminate\Http\JsonResponse as array
You can simply use json_decode()
to convert json object into a php array
$data = json_decode($data1);
echo $data->title; // Cable
It looks like you're trying to use a single function to return data for multiple endpoints (one json and one view). This is good except that shared function should return an array instead of a JsonResponse. The JsonResponse class isn't a JSON object, it is a Response object that has the data in addition to all the response data like headers, cookies, etc.
Update the index()
to return an array. From your comments it sounds like this is contained in a controller, but it is used in a different controller. This should live in its own class that is then called from any controller that needs it.
public function index()
{
// retrieve/generate data
return [ 'result' => true, 'title' => $title, 'orders' => $orders ];
}
Then in your json route do:
public function jsonEndpoint()
{
return response()->json($getProduct()->index());
}
Then in your blade route do:
public function bladeEndpoint()
{
$data1 = $getProduct->index();
$data = array(
'title'=> $data1['title'],
'Description'=>'This is New Application',
);
return view('view_name', $data);
}
The class Illuminate\Http\JsonResponse
indicates that your returned data is not an array but an object.
Based on that, you should do something like this:
$data1 = $getProduct->index();
// As $data1 is Illuminate\Http\JsonResponse
// you need to get the data in object format (not array)
$data = array(
'title'=> $data->title,
'Description'=>'This is New Application',
);
That should do it.
Note: if $data1
is null, then your json is bad formatted.
Try to use dd(your_object) or dump(your_object) to see exactly what's inside your object before sending it as on the response