dabadaba
dabadaba

Reputation: 9542

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?

Upvotes: 6

Views: 35208

Answers (3)

Shuvo
Shuvo

Reputation: 367

you can try this step...

set route...

Route::get('/json', [yourController::class, 'getJSON']);

and the method for get value as json format

public function getJSON(Request $request)
{

    $url = 'https://api******';

    $response = file_get_contents($url);
    $newsData = json_decode($response);


    return response()->json($newsData);         

}

Upvotes: 2

joshuahornby10
joshuahornby10

Reputation: 4292

Take a look at my package

https://github.com/joshhornby/Http

Hopefully makes it a little easier to call APIs

Upvotes: 1

Laurence
Laurence

Reputation: 60058

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);
});

Upvotes: 17

Related Questions