Okay so I have a following situation:
The system I am building is retrieving data from a REST api and saving that data into a database. What I am wondering is how could this be implemented and where would behaviour like this go in sense of Laravels structure (controller, model etc.)? Does Laravel have a built in mechanism to retrieve data from external sources?
Laravel lets you easily and quickly build RESTful APIs. This could be the back-end to a front-end web app, a data source for a mobile app, or a service for other apps or APIs.
Laravel's resource classes allow you to expressively and easily transform your models and model collections into JSON. Basically you can generate a nice json formatted data right from Eloquent.
Edit: Buzz hasn't been updated for over a year, it's recomended to now use Guzzle, see Mohammed Safeer's answer.
I have used Buzz package in order to make API requests.
You can add this package by adding it to the require
section in your composer.json
file.
{ require: { "kriswallsmith/buzz": "dev-master" } }
Then run composer update
to get it installed.
Then in Laravel you can wrap it in a class (perhaps a repository-like class) that handles making API request and returning data for your app to use.
<?php namespace My\App\Service; class SomeApi { public function __construct($buzz) { $this->client = $buzz; } public function getAllWidgets() { $data = $this->client->get('http://api.example.com/all.json'); // Do things with data, etc etc } }
Note: This is pseudocode. You'll need to create a class that works for your needs, and do any fancy dependency injection or code architecture that you want/need.
As @Netbulae pointed out, a Repository might help you. The article he linked is a great place to start. The only difference between the article and what your code will do is that instead of using an Eloquent model to get your data from your database, you're making an API request and transforming the result into a set of arrays/objects that your application can use (Essentially, just the data storage is different, which is one of the benefits of bothering with a repository class in the first place).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With