7

I am using Laravel 5.5.13.

My goal is to create an endpoint like this:

/api/items/{name}?kind={kind}

Where kind is optional parameter passed in by the query string.

My current routes in api.php looks like this:

Route::get('items', 'DisplaynameController@show'); 

My current controller is like this:

public function show(Request $request)
{
    if ($request->input('kind') {
        // TODO
    } else {
        return Item::where('name', '=', $request->input('name'))->firstOrFail();
    }
}

I

I am currently using $request->input('name') but this means I need to provide ?name=blah in the query string. I am trying to make it part of the route.

May you please provide guidance.

2 Answers 2

17

The $name variable is a route param, not a query param, this means that you can pass it directly to the function as an argument.

So, if your route is like this:

Route::get('items/{name}', 'DisplaynameController@show'); 

Your function should be like this:

public function show(Request $request, $name) // <-- note function signature
{   //                                 ^^^^^
    if ($request->has('kind'))
    {
        // TODO
    }
    else
    {
        return Item::where('name', '=', $name)->firstOrFail(); // <-- using variable
    }   //                              ^^^^^
}

Another option is to get the variable as a Dynamic Property like this:

public function show(Request $request)
{
    if ($request->has('kind'))
    {
        // TODO
    }
    else
    {
        return Item::where('name', '=', $request->name)->firstOrFail();
    }   //                              ^^^^^^^^^^^^^^
}

Notice that we access the name value as a dynamic property of the $request object like this:

$request->name

For more details, check the Routing > Route parameters and Request > Retrieving input sections of the documentation.

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

3 Comments

Oh interesting, thank you for helping with the docs. The first challenge to learning something new is to learning how to navigate the docs. I really appreciate it. So it is not possible to get query string parmeters auto binded?
@Blagoh for query params not yet, but Laravel can bind route params to match them to models as you can see here. All you need to do is type-hint the request on your controller method.
Thank you sir @HCK!
2

As stated in the documentation you should do:

public function show($name, Request $request)

Laravel will take care of the variable binding

1 Comment

Thank you sir. By any chance do you know a better way for me to do the $request->input('kind') check? Is this is the Laravel recommended way?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.