1

I have problem with my code, I can't fetch data from an API to display categories in client side the message "Trying to get property of non-object"

Here is my code: 1. Controller

<?php

namespace App\Http\Controllers\Category;

use GuzzleHttp\Client;
use App\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CategoryClientController extends Controller
{
 /**
 * Display the specified resource.
 *
 * @param  \App\Category  $category
 * @return \Illuminate\Http\Response
 */
public function show(Category $category)
{
    $client = new \GuzzleHttp\Client();

    // Create a request
    $request = $client->get('http://restfulapi.dev/api/categories');
    // Get the actual response without headers
    $response = $request->getBody();

    $categories = json_decode($response,true);

    return view('category.index', compact('categories'));
}
}
  1. View/index.blade.php to render the resultsThis is the result when i dd

    <!DOCTYPE html>
    <html>
    <head>
       <title>List of Categories</title>
    </head>
    <body>
    
    @foreach ($categories as $category)
    {{$category->name}}
    {{$category->description}}
    @endforeach
    
    </body>
    </html>
    
lloiacono
  • 3,504
  • 2
  • 27
  • 40
Ogi
  • 13
  • 7

1 Answers1

2

since your response is not Std Object type, you need to use array notation in view when dispaying data, like:

@foreach ($categories as $category)
    {{$category['name']}}
    {{$category['description']}}
@endforeach

or return std object from your controller, as:

$categories = json_decode($response); //remove true
Sudhir Bastakoti
  • 94,682
  • 14
  • 145
  • 149