Fahim Uddin
Fahim Uddin

Reputation: 701

How to read JSON from api url with laravel 5.5

How to read JSON from api url with laravel 5.5 while maintaining the MVC format.

I have searched a lot about it but could not find any on point answer.

There are lots of ways to read/post JSON using ajax, but that will harm the architecture, so I want to use controller to parse JSON and then pass to view. or maybe is there a way to parse json into model first ?

There is also a plain solution of decoding JSON though simple php like this :

$rUrl = 'http://example.com/api/products';

$data = json_decode(file_get_contents($rUrl), true);

return view('mydata')->withData($data);

But Is there any better way to handle this in laravel ? and in which other ways I can maintain header and JSON results in laravel ?

is my question is not clear please comment to correct it. any help would be appreciated. Thanks in Advance !

Upvotes: 0

Views: 11878

Answers (1)

Vision Coderz
Vision Coderz

Reputation: 8078

In laravel you can go for Guzzle Package.

https://github.com/guzzle/guzzle

if you are using get request then you can go for file_get_contents.But if you are sending post request then better you can use curl

file_get_contents - It is a function to get the contents of a file(simply view source items i.e out put html file contents).

curl - It is a library to do more operations, for example get the contents like file_get_contents, sending and receiving data from one site to another site and it also supports different types of protocols like http, https, ftp, gopher, telnet, dict, file, and ldap. curl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading HTTP form based upload, proxies, cookies.

If you are looking for mvc pattern then you can create static methods in helper class to handle different type of request so you can call these methods

Guzzle documentation

http://docs.guzzlephp.org/en/stable/

http://itsolutionstuff.com/post/laravel-guzzle-http-client-post-request-exampleexample.html

http://www.expertphp.in/article/laravel-php-guzzle-http-client-get-and-post-request-example

https://www.youtube.com/watch?v=y6Zz-kgf4L8

Upvotes: 1

Related Questions