Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Get" route with query string and custom params

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.

like image 633
Blagoh Avatar asked Nov 12 '17 21:11

Blagoh


1 Answers

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.

like image 152
Kenny Horna Avatar answered Oct 20 '22 13:10

Kenny Horna