Home > Software engineering >  how to get data from external API to datatable with using Laravel
how to get data from external API to datatable with using Laravel

Time:11-16

ErrorException

Invalid argument supplied for foreach() (View: D:\Projects\Laravel\Laravel-api\resources\views\new.blade.php)

<table >
    <thead>
    <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Contact</th>
        <th>City</th>
        <th>Note</th>
        <th>Item Details</th>
        <th>Contact No(SMS)</th>

    </tr>
    </thead>

    <tbody>
        @foreach($data as $item)
                <tr>
                    <td>{{$item->sName}}</td>

                    <td>{{$item->email}}</td>
                    <td>{{$item->contact}}</td>
                    <td>{{$item->city}}</td>
                    <td>{{$item->note}}</td>

                    <td>{{$item->itemDetails}}</td>
                    <td>{{$item->whatsappNo}}</td>
                    <td>
                </tr>
        @endforeach
    </tbody>
</table>

Controller

    public function displayData(){


            $Client = new GuzzleHttp\Client();
            $res = $Client->request('GET','http://127.0.0.1:8080/api/suppliers');
            $data = $res->getBody()->getContents();

            return view('new',compact('data'));
         
    }
  1. How to retrieve data from a External API to datatable in Laravel 17

CodePudding user response:

getContents() returns a string and not an array. If it is a json string, you have to decode it like $data = json_decode($data); before passing it to your view.

public function displayData() {

    $Client = new GuzzleHttp\Client();
    $res = $Client->request('GET','http://127.0.0.1:8080/api/suppliers');
    $data = $res->getBody()->getContents();
    $data = json_decode($data);

    return view('new',compact('data')); 
}
  • Related