Comparing Laravel’s request()->input(), request()->get(), and request()->name methods of retrieving form data.

If you’ve been around Laravel for a while, you might have seen there are three ways in controllers to retrieve inputs from the submitted form. For example, if you are trying to retrieve the name of a user from a form, user controller might have one of the following lines of code:

Now the question is what the difference is between these three methods, and which one is preferred?

The input() method

From the Laravel 5.3 docs, there are three distinctions that set the input() method apart:
Regardless of the HTTP verb, the input method may be used to retrieve user input:

You may pass a default value as the second argument to the input method. This value will be returned if the requested input value is not present on the request:

When working with forms that contain array inputs, use “dot” notation to access the arrays:

To summarize:

  • The input() method can be used with any HTTP verb to retrieve data (both GET or POST request).
  • A default value can be set when using the input() method by adding a 2nd (optional) parameter.
  • You can use dot notation to access forms that have names that are arrays. For example, if you were using a form with a name like this:

    then your controller can retrieve that form input using

The dynamic property
When using dynamic properties, Laravel will first look for the parameter’s value in the request payload. If it is not present, Laravel will search for the field in the route parameters. The dynamic property will return the input whether the input is coming from a GET or POST request.

The get() method
The get() method can be confused with the Eloquent and Query Builder get() methods that retrieve results from a query. The below code block is a bit blurry in terms of what get() method is retrieving data from the database and which one is retrieving data from the form:

You might think that it’s not so bad having a couple of different get() methods, even if they are all frequently used. Which means the end result could end up looking something like this:

Leave a Reply

Your email address will not be published. Required fields are marked *