Arafat Rahman
Arafat Rahman

Reputation: 117

How can I get only data from a response and show it into a blade template in Laravel 8?

Controller code

 public function add_employee(){

    $covid_statuses = Http::get("http://localhost:8000/api/v1/covid/status");


     $covid_statuses =  json_decode($covid_statuses['data'],200);
    //  $covid_statuses =  json_encode($covid_statuses['data'],200);

     return view('admin.hr.os.employee.add_employee',compact('covid_statuses'));


    // return view('admin.hr.os.employee.add_employee',[
    //     'covid_statuses' => $covid_statuses,
    //     // 'covid_statuses' => json_decode($covid_statuses['data']),
    // ]);

}

The main respone is like {"data":[{"id":1,"name":"1st dose completed"},{"id":2,"name":"2nd dose completed"}],"success":true,"status":200}

When I decode only data, and pass into blade and in blade I use to debug like @foreach($covid_statuses as $covid_status) {{$covid_status}} @endforeach

but I got

json_decode() expects parameter 1 to be string, array given

When I use encode then I got

Invalid argument supplied for foreach()

How Can I solve this issue?

Upvotes: 0

Views: 711

Answers (1)

Mátyás Grőger
Mátyás Grőger

Reputation: 1682

You could use array_walk for that purpose. Try:

    $covid_statuses = array_walk($covid_statuses['data'], function(&$item, &$id) { 
        $item = $item['name'];
        $id = $item['id'];
});

Like this, the array will only contain the names of the covid cases, by it will have the same id as in the original request

Upvotes: 1

Related Questions