#development #laravel #php

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:

1if ($request->has('name')) {
2    // Will only check if the request has a parameter with this name
3    // Doesn't check if the parameter contains a value
4}

To get the actual value, you can use input. This returns the value of the parameter:

1// If not present, returns null
2$name = $request->input('name');
3
4// If not present, returns 'Sally'
5$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:

1// Given the url: http://localhost/
2$name = $request->input('name', 'Sally'); // => returns 'Sally'
3
4// Given the url: http://localhost/?name=
5$name = $request->input('name', 'Sally'); // => returns null
6
7// Given the url: http://localhost/?name=pieter
8$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:

1if ($request->filled('name')) {
2    // Name is present and contains a value
3}

There are many more things you can learn about requests in the official documentation.