sesc360
sesc360

Reputation: 3255

Retrieving get parameters from URL in Laravel

I created an URL String:

http://SERVER/v1/responders?latitude=48.25969809999999&longitude=11.43467940000005

a route:

Route::get('/responders', 'Responders\APIResponderController@index');

and a controller:

public function index(Request $request) {

    // Get Latitude and Longitude from request url
    $latitude = $request["latitude"];
    $longitude = $request["longitude"];

    $responders = new Responder();

    if(!isset($latitude) & !isset($longitude)) {
    }

But the result is not what I expected. The parameters in the URL string are not being parsed withing the controller. Do I parse them in a wrong way?

I tried to dump my input with dd($request->all()); but the output is NULL. As the URL is sent correctly, I wonder where the data gets lost. Is my route file incorrect?

Update Could it be my nginx config??

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /var/www/mfserver/public;
    index index.php index.html index.htm;

    charset utf-8;

    server_name SERVER;

    location / {
        try_files $uri $uri/ /index.php?query_string;
    }

    error_page 404 /index.php;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /var/www/mfserver/public;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
    }
}

Upvotes: 0

Views: 2162

Answers (4)

patricus
patricus

Reputation: 62248

You have a typo in your nginx config. In your location definition, your query_string variable is missing the leading $. Because of this, your original query string is getting re-written with the plain text of query_string. This is why your request data is showing array:1 [▼ "query_string" => "" ] when you dump it.

Update your config to:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

Upvotes: 1

Abhishek
Abhishek

Reputation: 3967

Try this:

$inputs = $request->all();

And then :

$latitude = $inputs['latitude']

$longitude = $inputs['longitude']

Upvotes: 1

Pascal
Pascal

Reputation: 296

The most common way would be

$latitude = $request->input("latitude");

Upvotes: 0

Claudio King
Claudio King

Reputation: 1616

This should work, adapt it to your needs.

public function index(Request $request) {
    if(!$request->has('latitude') || !$request->has('longitude')) {
        // code if one or both fields are missing
    }

    // Get Latitude and Longitude from request url
    $latitude = (float)$request->input('latitude') ;
    $longitude = (float)$request->input('longitude');

    // other code here

}

Upvotes: 0

Related Questions