0

How to pass array of GET parameters to the controller?

This is my route file routes/web.php:

<?php
use Illuminate\Support\Facades\Route;
use GuzzleHttp\Client;

Route::get('/ids', 'Parser@getIds');

And my controller 'app/Http/Controllers/Parser.php':

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class Parser extends Controller
{
  public function getIds(Request $request) {
    return response()->json($request); // ???
  } 
}

So, I expect to get an array of parameters like this:

$ids = [1,2,15,25];

But if I pass GET array to my route path: http://example.com/ids?ids[]=1&ids[]=2&ids[]=15&ids[]=25

I get an empty request object anyway:

{"attributes":{},"request":{},"query":{},"server":{},"files":{},"cookies":{},"headers":{}}

3
  • 1
    The response is fine. The method json return a array encode to json. If you want just return the response. you can do it this: return $request; and this return you request. Commented Mar 13, 2021 at 22:20
  • 1
    I coded your example and it's working without any error or result is as expected. Commented Mar 14, 2021 at 2:44
  • @MAY appreciating your help. I don't know why but I had an empty 'request:{}' object in json response as I described above. And then $ids = request('ids', []); worked fine for me. Commented Mar 14, 2021 at 4:35

1 Answer 1

1

There is few ways to get data from GET. Try something like that:

$ids = request('ids', []); // global helper, empty array as default

or:

$ids = $request->input('ids', []); // via injected instance of Request

More info you can get in documentation

Sign up to request clarification or add additional context in comments.

3 Comments

This is correct, but more specifically, it should be request()->query('ids'); or $request->query('ids') if you are injecting the Request in the method. You can also pass a default value. query('ids', [])
request('ids') also works, but it is good notice to pass a default value. it will be helpful in this case.
Thank you so much. $ids = request('ids', []); works well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.