Chris Mellor
Chris Mellor

Reputation: 377

Echo Data From Collection to Blade View

I am simply (for my own testing purposes) trying to take data from a collection and pass it to a view. I am using Laravel.

I am getting my data from the GitHub API, converting it and putting it in a collection. From here it's passed to a view, but I can't output each individual field.

Here's some code:

$httpClient = new Client();

$response = $httpClient->get('https://api.github.com/users/<randomuser>');

$json = json_decode($response->getBody(), true);

$collection = collect($json);

return view('github')->with('github', $collection);

and my Blade file is

@foreach ($github as $git)
  {{ $git }}
@endforeach

Now I thought it would be something as simple as {{ $git->email }} to output it, but I don't think the array keys are been sent (?)

Can anybody point me in the right direction of where I am going wrong?

Thanks in advance.

-Chris

Upvotes: 2

Views: 5099

Answers (4)

Cristobal G.
Cristobal G.

Reputation: 11

When you are working with Laravel try to check if you have the correct structure before trying to manipulate it.

In this case, check that:

  • You are getting what you expect in $response after call $httpClient->get (if you are using Guzzle).
  • You have a $json with the structure that you expect to receive.
  • You have a Collection instance after calling collect().

You can use dd() or var_dump() to see what data structure you have. What´s probably happening is that you don´t have the structure that you think.

Upvotes: 0

KmasterYC
KmasterYC

Reputation: 2354

Simple use get() method in your blade

$github->get('login')

Upvotes: 1

user1669496
user1669496

Reputation: 33058

Because it's a key => val array, you should loop it as such...

@foreach ($github as $key => $val)
    Key: {{ $key }}  ~~ Value: {{ $val}} <br />
@endforeach

However if you are looking to just grab the email, use the Collection's get method.

$email = $github->get('email')

Upvotes: 2

Raunak Gupta
Raunak Gupta

Reputation: 10809

Try this, in your controller use View and in function

$data['github_data'] = $collection; return view('github', $data);

and in blade

{{ dd($github_data) }}

Upvotes: 0

Related Questions