Since I am completely new in Laravel, I have a problem pretty complicated for me.
I have controller file ApiHandlerController like this:
<?php namespace AppHttpControllers; use IlluminateHttpRequest; use IlluminateSupportFacadesHttp; use GuzzleHttpClient; class ApiHandlerController extends Controller { // public function index() { $client = new Client([ // Base URI is used with relative requests 'base_uri' => 'http://jsonplaceholder.typicode.com/todos', ]); $response = $client->request('GET', '/todos'); //get status code using $response->getStatusCode(); $body = $response->getBody(); $arr_body = json_decode($body); return view('myview', $arr_body); } } ?>
myview.blade.php as a view file:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Todo</title> <link rel="shortcut icon" type="image/x-icon" href="icon.ico"> <meta name="description" content="HTML, PHP, JSON, REST API"> <style>table, th, td {border: 1px solid black;}</style> </head> <body> <table style="width:100%"; class="data-table"> <tr> <th>User ID:</th> <th>ID:</th> <th>Title:</th> <th>Completed</th> </tr> <?php foreach ($arr_body as $value) { ?> <tr> <td><?php echo $value -> userId ?> </td> <td><?php echo $value -> id ?> </td> <td><?php echo $value -> title ?> </td> <td><?php echo $value -> completed ?> </td> </tr> <?php } ?> </table>
And web.php file with route:
Route::get('myview', function () { return view('myview'); });
My question is:
How to show result of todos from jsonplaceholder.typicode.com in this blade (view) file? Currently, it’s not possible, and every time I try this is an error:
ErrorException Undefined variable: arr_body (View: C:xampphtdocsTodoListresourcesviewsmyview.blade.php) Thank you guys in advance!
Advertisement
Answer
To show array type data in blade…
First edit your controller code.
From:
return view('myview', $arr_body);
To:
return view('myview')->with('arr_body', $arr_body);
Below is core php syntex.
<td><?php echo $value['userId'] ?> </td>
Laravel syntex
<td>{{$value['userId']}}</td>
Hope this will be useful.