1

Just as a learning exercise, I'm creating a REST API in Laravel 7.1. I'm having trouble figuring out how to parse the query string parameters in route methods. I've read over the documentation here, and it shows how to add parameters into the path:

Route::get('user/{id}', function ($id) {
    return 'User '.$id;
});

However I don't see where you can get query parameters from the request URL. In my toy code, I want to add a route to add a new car to inventory:

Route::post('/inventory/add/{make}/{model}/{year}', function ($make, $model, $year) {
    return \App\Inventory::create($model, $color, $trim, $accessories);
});

I want to specify parameters such as color, trim, and accessories through the query string, like so:

http://example.com/inventory/add/ford/focus/2020?color=red&trim=sport&accessories=chrome-wheels

How do I get the query parameters out of the Route::post method?

Edit I suppose this architecture may not be the optimal way of adding this extra information, but since I am trying to learn laravel, I am using it as an example. I am interested in learning how to get the query parameters moreso than how to improve the architecture of this learning example.

2 Answers 2

5

In Route::post you don't need set the parameters in route. Just use:

Route::post("your-route", "YourControllerController@doSomeThing");

So, in app/Http/Controllers/YourControllerController.php file:

class YourControllerController extends Controller {

public function doSomeThing(Request $request)
{
    echo $request->input('param1');
    echo $request->input('param2');
    echo $request->input('param3');
}
Sign up to request clarification or add additional context in comments.

Comments

2

You just need to inject the request instance into your handler (whatever a closure or controller method) and then ask for your parameters.

$color = $request->query('color', 'default-color');

//And so on...

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.