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

Tutorial last revisioned on August 18, 2022 with Laravel 9
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.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 60 courses (1084 lessons, total 42 h 44 min)
  • 80 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials