MasterPHP.in
Try Compiler →
Laravel Tutorial

The Request Object and Handling Input in Laravel


Your invoice list page works, but the owner wants filters. Show only paid invoices, search by client name, and let the user choose how many rows to see per page. The browser sends all of this in the URL, something like /invoices?status=paid&search=Sharma&per_page=25.

In plain PHP you would reach for $_GET, and later $_POST for forms. You would check whether each key exists, convert text to numbers, and hope nobody sends something strange. Every page repeats the same defensive code, and one missing check shows up as a warning on a live site.

Laravel wraps all of this in one object called the request. It knows where each value came from, gives you safe defaults and converts types for you. In this lesson you will learn how to get the request object and how to read input from it.

 

Plain PHP vs the Laravel Request

Here is the plain PHP way of reading the filters from the URL:

$status  = $_GET['status'];
$perPage = $_GET['per_page'] ?? 10;

If the visitor opens /invoices without a status, the first line gives this warning:

Warning: Undefined array key "status"

You must remember to add ?? 'all' everywhere. The values are always text, even for numbers. And $_GET and $_POST are two separate arrays, so JSON data sent by a mobile app is not in either of them.

The Laravel request object solves all three problems with one consistent set of methods, which work the same way whether the data arrives in the URL, in a form or as JSON.

 

Getting the Request Object

The Request class lives in Illuminate\Http. The easiest way to get it is to type-hint it in your controller method. This is dependency injection, which you learned in the Dependency Injection lesson, and you have already seen Request $request in the generated resource controller. Laravel creates the object for the current visit and passes it in.

Update the index() method of your InvoiceController:

use Illuminate\Http\Request;

public function index(Request $request)
{
    return [
        'status'   => $request->query('status', 'all'),
        'search'   => $request->query('search'),
        'per_page' => $request->integer('per_page', 10),
        'invoices' => $this->invoiceService->all(),
    ];
}

Visit this address in your browser:

http://localhost:8000/invoices?status=paid&search=Sharma&per_page=25

You will see the values echoed back in the JSON:

{
  "status": "paid",
  "search": "Sharma",
  "per_page": 25,
  "invoices": { ... }
}

Visit /invoices without any filters and you get the defaults, all and 10, with no warnings. We are only reading the values here. Using them to filter real data comes in the Query Builder and Eloquent chapters.

There is also a global request() helper that returns the same object from anywhere in your code. Injecting the request, as above, makes it clear what your method needs, so prefer injection inside controllers.

 

Reading Input

Input can reach your app in three places. Laravel treats them as one pool of values, so you do not need to care about the source most of the time:

Query string:   /invoices?status=paid
Form body:      POST with status=paid in the body
JSON body:      POST with {"status": "paid"} in the body

input(): Values from Anywhere

The input() method reads a value from the query string, the form body or a JSON body. The second argument is a default value, used when the key is missing:

$client = $request->input('client');
$status = $request->input('status', 'all');

You can also read everything at once as an array:

$data = $request->all();

Because input() checks every source, the same controller code works for a browser form and for a mobile app sending JSON.

 

query(): Values from the URL Only

The query() method reads only from the query string and ignores the body. Use it for filters, search words and page numbers, where you know the values live in the URL:

$page = $request->query('page', 1);

This matters when a form posts to /invoices?status=paid and also contains a field called status. With input() you cannot be sure which value you get back, but query() always reads the URL.

 

Typed Helpers

Everything that arrives from a URL or a form is text. The value 25 is really the string "25". Laravel gives you helpers that convert the value for you:

$perPage = $request->integer('per_page', 10);   // 25 as a real number
$isPaid  = $request->boolean('paid');           // true for 1, "1", "true", "on", "yes"
$client  = $request->string('client')->trim();  // a text object with helper methods
$dueDate = $request->date('due_date');          // a date object, or null if empty

The boolean() helper is especially useful for checkboxes, which send the text on when ticked. The date() method also accepts a format, which helps with Indian-style dates:

$dueDate = $request->date('due_date', 'd/m/Y');   // 25/12/2026

 

Nested and JSON Input

Data can be nested. A mobile app creating an invoice might send this JSON:

{
  "client": "Sharma Traders",
  "items": [
    { "name": "Printer Paper", "qty": 10 },
    { "name": "Stapler", "qty": 5 }
  ]
}

Use dot notation to reach inside it. A star means “every item”:

$request->input('client');           // Sharma Traders
$request->input('items.0.name');     // Printer Paper
$request->input('items.*.qty');      // [10, 5]

Laravel reads JSON bodies only when the sender includes the Content-Type: application/json header. You will work with JSON in detail in the Building REST APIs chapter.

 

Dynamic Properties

You may also see input read as a property, like this:

$client = $request->client;

It works, but it is easy to confuse with real properties of the request object, and it also falls back to route values. Prefer input('client'), which says exactly what you mean.

 

Checking Whether Input Exists

Sometimes you only want to apply a filter if the user actually provided it. Laravel has three checks for this, and they differ in one important way:

$request->has('search');      // true if the key is present, even when empty
$request->filled('search');   // true only if the key is present and not empty
$request->missing('search');  // true if the key is not present at all

Consider the address /invoices?search=. The key search is in the URL, but it has no value. In this case has('search') is true, while filled('search') is false. For filters, filled() is almost always the one you want.

You can also check several keys at once with hasAny(['status', 'search']).

 

Getting Only Part of the Input

You can ask for specific keys, or for everything except some keys:

$data = $request->only(['client', 'amount']);
$data = $request->except(['_token']);

The only() method returns just the keys you list and skips any others that were sent. This is the safe habit. A user can send extra fields that your form never showed, for example status=paid on a create request. If you pass $request->all() straight into your database, those extra fields come along. You will study this danger in the Mass Assignment lesson in the Eloquent chapter, but the habit starts here: pick the values you expect.

 

Reading Information About the Request

The request object knows more than the input. It also describes how the visit was made:

$request->method();                // "GET", "POST" ...
$request->isMethod('post');        // true or false

$request->path();                  // "invoices"
$request->is('invoices/*');        // true for invoices/1001, invoices/create ...
$request->url();                   // http://localhost:8000/invoices
$request->fullUrl();               // same, with ?status=paid&...

$request->header('Accept-Language');
$request->bearerToken();           // the token from "Authorization: Bearer ..."
$request->userAgent();             // the browser name
$request->ip();                    // the visitor's IP address
$request->expectsJson();           // true if the client wants JSON back

The is() method is the URL-based cousin of the routeIs() method you used in the Named Routes lesson. Treat headers and the IP address as information only. A visitor can fake both, so never use them to decide who is allowed to do something.

 

Adding Default Values to the Request

The merge() method adds values to the request before the rest of your code reads it. The mergeIfMissing() method adds them only if the key is not already there:

$request->mergeIfMissing(['status' => 'all']);

$status = $request->input('status');   // "all" when none was sent

This is handy when a service or another class expects a value to always exist.

 

What Laravel Cleans Up for You

Every request passes through two pieces of middleware that are active by default. One trims the spaces from the start and end of every text value. The other turns empty strings into null. So a visitor who types " Sharma Traders " gives you "Sharma Traders", and an empty search box gives you null.

This is why $request->input('search') returns null and not an empty string for a blank field. You will learn what middleware is in the Middleware Basics lesson later in this chapter.

 

What Comes Later

Reading input is only the first step. The Request object gives you the data, but it does not check whether the data is correct. An amount of -500, an invoice for a client who does not exist, or a date written as text will pass through untouched. Checking input is called validation, and you will learn it in the Forms & Validation chapter. File uploads, cookies and the session data also live on the request, and each has its own lesson.

 

Common Mistakes

Mistake 1: Forgetting to Import the Request Class

public function index(Request $request)

If the use Illuminate\Http\Request; line is missing, PHP looks for a class named Request inside your controller’s namespace, and Laravel throws:

Illuminate\Contracts\Container\BindingResolutionException: Target class [App\Http\Controllers\Request] does not exist.

Add the import at the top of the file.

 

Mistake 2: Treating a Number as a Number

if ($request->input('per_page') === 25) {
    // never runs
}

The value is the text "25", so a strict comparison with the number 25 is false. No error appears, and the condition just never runs. Use $request->integer('per_page') to get a real number.

 

Mistake 3: Using has() When You Mean filled()

if ($request->has('search')) {
    // runs even for /invoices?search=
}

An empty search box still sends the key. Your code then filters by an empty word and returns nothing. Use filled('search') when an empty value should count as missing.

 

Mistake 4: Reading a Form Value with query()

A form posts client=Sharma Traders in its body. Calling $request->query('client') returns null, because that method only reads the URL. Use input() for form and JSON data.

 

Mistake 5: Passing $request->all() to the Database

It is the shortest line to write, and it quietly accepts any field a user decides to add. Use only() to take just the fields you expect, and check them with validation as soon as you learn it.

 

Mistake 6: Trying to Test a POST by Typing the URL

The address bar always sends GET. If you point a tool at a POST route in web.php without a CSRF token, Laravel replies with 419 | Page Expired. This is normal protection, not a bug. For now, practice with GET query strings, since input() reads them too. You will send real POST requests from forms in the Forms & Validation chapter.

 

Quick Summary

  • The Request object holds everything about the current visit, including input, headers and the URL.
  • Get it by type-hinting Illuminate\Http\Request in a controller method.
  • input() reads from the query string, form body and JSON, with an optional default value.
  • query() reads from the URL only.
  • Use integer(), boolean(), string() and date() to get values in the right type.
  • Use dot notation like items.0.name for nested data, and items.*.qty for every item.
  • has() checks that a key exists, filled() checks that it also has a value, and missing() checks that it is absent.
  • Use only() and except() to take part of the input, and avoid sending all() to the database.
  • Methods like method(), path(), is(), fullUrl() and header() describe the request itself.
  • Spaces are trimmed and empty strings become null by default.
  • Reading input does not check it. Validation comes in a later chapter.

 

What’s Next

You now know how data comes into your app. The next question is how your app sends something back. So far we have returned strings and arrays, and Laravel turned them into responses for us. In the next lesson, Responses: Views, JSON & File Downloads, you will learn how to control exactly what the browser receives, including status codes, JSON and downloadable invoice files.

Frequently Asked Questions

The input() method reads from the whole request, including the query string, the form body and JSON. The query() method reads only from the query string in the URL. Use input() for submitted data and query() for filters and page numbers.
It is safe for reading and debugging, but not for saving straight to the database. A user can add extra fields to a request, and all() will include them. Use only() to pick the fields you expect, and add validation later.
Both give you the same object. Injection makes the needs of your method clear at a glance and is easier to replace in tests, so it is preferred in controllers. The helper is useful in places where injection is awkward, such as a small helper function.
Everything sent through a URL or a form is text, so the value 25 arrives as the string 25. Use the integer() method to convert it, or boolean() for checkbox values. This avoids bugs in strict comparisons.
Use input() with dot notation, such as input(‘client’) or input(‘items.0.name’). The sender must include the Content-Type: application/json header so that Laravel knows to read the body as JSON. The same input() code also works for normal form data.

Share this tutorial