Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

boyjarv's avatar

Retrieve an input form the query string

I am trying to get ?limit=50 from my query string reading here:

https://laravel.com/docs/8.x/requests#retrieving-input

my api path: api/todos goes here: App\Http\Controllers\TodoController@index

index method in TodoController

public function index()
    {
        //
        $todos = $this->user->todos()->get(['id', 'title', 'body', 'completed', 'created_by']);
        return response()->json($todos->toArray());
    }
0 likes
8 replies
tykus's avatar

You can get query string params using request() helper, passing the key, i.e. request('limit'):

I have expanded the query for clarity

public function index()
{
        $todos = $this->user
		->todos()
		->when(request()->has('limit'), fn ($builder) => $builder->take(request('limit'))
		->get(['id', 'title', 'body', 'completed', 'created_by']);
        return response()->json($todos->toArray());
}

This line when(request()->has('limit'), fn ($builder) => $builder->take(request('limit')) checks for the presence of a limit key on the Request, and then applys the limit on the query; otherwise, there is no limit on the query.

4 likes
boyjarv's avatar

thanks, I? tried this and now I get:

{message: "Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::toArray()",…} exception: "BadMethodCallException" file: "/Users/johnmichael/playground/laravel/choosapi/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php" line: 50 message: "Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::toArray()"

Snapey's avatar

Did you do it as shown or did you 'adapt' it ? Looks like you forgot the get()

boyjarv's avatar

I added a closing parenthesis to the end of the get

boyjarv's avatar

sorted! put parenthesis in wrong place!

jlrdw's avatar

@boyjarv could you please show as solved, I read through all not realizing you solved it.

Please or to participate in this conversation.