How to get Laravel's request parameters
Learn how to get query parameters in Laravel with an example.
Laravel's request parameters can be accessed through the $request
object. This object provides methods to retrieve all incoming request data in an HTTP request, including query string parameters, form fields, route parameters, and files. The $request
object can be accessed via the controller action or a Request
class.
Using the $request Object
When working in a controller action, the $request
object can be used directly. Here is an example of how to retrieve the value of a query string parameter named name
:
public function show(Request $request)
{
$name = $request->query('name');
// ...
}
The query()
method of the $request
object retrieves the value of a query string parameter. If the parameter does not exist, the query()
method will return null
.
The $request
object also provides a query()
method that accepts a default value as its second argument. The default value will be returned if the query string parameter does not exist. Here is an example of how to use the query()
method with a default value:
public function show(Request $request)
{
$name = $request->query('name', 'Guest');
// ...
}
In this example, the $name
variable will be set to Guest
if the name
query string parameter does not exist.
Using the Request Class
The Request
class provides a global accessor to retrieve request data. It can be used to access query string parameters, form fields, route parameters, and files. Here is an example of how to use the Request
class to retrieve the value of a query string parameter named name
:
public function show()
{
$name = Request::query('name');
// ...
}
The Request
class also provides a query()
method that accepts a default value as its second argument. The default value will be returned if the query string parameter does not exist. Here is an example of how to use the query()
method with a default value:
public function show()
{
$name = Request::query('name', 'Guest');
// ...
}
In this example, the $name
variable will be set to Guest
if the name
query string parameter does not exist.