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:

<?php

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:

<?php

// 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:

<?php

// 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:

<?php

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.

Related Posts

  • Optimising large whereIn queries in Laravel
  • Customising lazy-loading prevention in Laravel
  • Laravel Service Provider in Simple English
  • The giveConfig function in Laravel
  • Testing for equal json strings in Laravel tests