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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With