Feature-Request

Differences: $request->get() vs $request->input() vs request() vs get_data()

How do you handle POST data in your store() or update() methods? Seems like a simple question, but actually there are so many options!

See this code:

Any thoughts? Do you know the difference?

Ok, let’s ignore data_get() for now, cause it’s primary purpose is not about requests – it just retrieves a value from a nested array or object.

Next. In general, for most cases, all of those methods do the same thing. Difference are in subtle cases, let’s look through them.

$request->get() vs $request->input()

In this case, input() is a little more powerful, cause it takes the nested data.

Remember data_get() we mentioned before? Actually, $request->input() combines $request->get() with data_get() helper.

Official Laravel documentation uses ->input() method and doesn’t even mention ->get().

Direct property

What about $request->email, is that wrong?
Again, let’s refer to official docs:

  • input() method will work regardless of the HTTP verb
  • input() method retrieves values from entire request payload (including the query string)

Now, what does it say about $request->name?

You may also access user input using dynamic properties on the Illuminate\Http\Request instance. 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.

request() helper

This is just one helper out of dozens available – see documentation:

The request function returns the current request instance or obtains an input item:

So basically, it’s just a shortcut for $request->input().

And yes, don’t forget that you can provide default value, in case that input item is missing.
You can also do it with $request->input().

So, a little more clear? But anyway, in 99% of the cases it’s a matter of preference, which method to use.

Liked the article? Maybe you need help with your Laravel project?
Our LaravelDaily Team can help!

Leave a Reply

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