Search code examples
phpjsonlaravellaravel-4response

Getting the JSON reponse from an API with Laravel


I am just messing with APIs and now I'm trying to use Google Directions API in my app.

I made a form to get the user's input and retrieve this data and create the URI just in the routes.php file:

Route::get('/directions', function() {
    $origin = Input::get('origin');
    $destination = Input::get('destination');

    $url = "http://maps.googleapis.com/maps/api/directions/json?origin=" . $origin . "&destination=" . $destination . "&sensor=false";
});

That URL's response is a JSON. But now, how am I supposed to store that response with Laravel? I have been looking at the Http namespace in Laravel and I didn't find a way. If it can't be done with Laravel, how can it be done with plain php?


Solution

  • You can use file_get_contents()

    Route::get('/directions', function() {
        $origin = Input::get('origin');
        $destination = Input::get('destination');
    
        $url = urlencode ("http://maps.googleapis.com/maps/api/directions/json?origin=" . $origin . "&destination=" . $destination . "&sensor=false");
    
        $json = json_decode(file_get_contents($url), true);
    
        dd($json);
    });