We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
There are many different ways in Laravel to get parameters from the request and to check if the parameter is present or not. There are however small subtleties in how they work.
Let's start with the has
function:
if ($request->has('name')) {
// Will only check if the request has a parameter with this name
// Doesn't check if the parameter contains a value
}
To get the actual value, you can use input
. This returns the value of the parameter:
// If not present, returns null
$name = $request->input('name');
// If not present, returns 'Sally'
$name = $request->input('name', 'Sally');
The caveat with input
is that the default value is only returned if the key isn't set in the query string. If it's set and contains an empty value, null
will be returned:
// Given the url: http://localhost/
$name = $request->input('name', 'Sally'); // => returns 'Sally'
// Given the url: http://localhost/?name=
$name = $request->input('name', 'Sally'); // => returns null
// Given the url: http://localhost/?name=pieter
$name = $request->input('name', 'Sally'); // => returns 'pieter
The proper way to check if a request parameter contains a value is by using the filled
method:
if ($request->filled('name')) {
// Name is present and contains a value
}
There are many more things you can learn about requests in the official documentation.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.