Norway


How do you handle POST 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 ?

Ok, let’s ignore data_get() for now, cause it’s 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 ( the query string)

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

You may also access user input using dynamic properties on the IlluminateHttpRequest 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('', $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.

The post Differences: $request->get() vs $request->input() vs request() vs get_data() appeared first on Laravel Daily.



Source link

No tags for this post.

LEAVE A REPLY

Please enter your comment!
Please enter your name here