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:

public function store(Request $request) {
  $email = $request->input('email'); // option 1
  $email = $request->get('email'); // option 2
  $email = $request->email; // even more simple?
  $email = request('email'); // there's also helper
  $email = data_get($request, 'email'); // did you even know this function?
}

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.

$name = $request->input('products.0.name'); // this will work
$name = $request->get('products.0.name'); // this will NOT work
$name = $request->get('products')[0]['name']; // this will work instead

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:

$request = request();
$value = request('key', $default = null);

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.

Like our articles?
Check out our Laravel online courses!

3 COMMENTS

  1. This is a big problem with Laravel (and every other ‘friendly’ framework it seems). 10 ways to do any single thing, all of which need to be tested. Then you see code with input() and get() in it, etc.

    Pick something and stick with it.

    Laravel user for 3 years, multiple apps in production.

LEAVE A REPLY

Please enter your comment!
Please enter your name here