Home > other >  Performance different between various request methods in Laravel
Performance different between various request methods in Laravel

Time:11-18

on laravel, there is a specific class named Illuminate\Http\Request which provided an object-oriented way to interact with HTTP request which are send by client-side

it can be accessed by two methods as follows,

$name = $request->input('name');
$name = $request->name;

which one is the most efficient way to get the request?

CodePudding user response:

The first one with input() is the mainly documented way of doing it, so I'd recommend using it as the functionnality is quite well established and the behavior is quite known.

The second one is a syntaxic sugar that map unexisting properties to inputs. It may be more concise however it uses a magic method call that will be potentially slower (check that a property exist, recognise it doesn't, resolve the magic call and execute the magic call).

However, while the performance difference is quite negligible for most usages imho, I'll not recommend using the second method anyway. As the Request class scemantics may change in future versions, you have no guarantee that a property will not be created with the same name as an input used in your application. This may or may not create bugs when upgrading the framework down the line as all your code will now be referencing this property instead of the inputed value as you intend it to.

CodePudding user response:

Those methods aren't the only ones in Laravel but the method

$name = $request->input('name');

you must be aware that using unvalidated data directly in your controller is also considered a security vuln. You should use this instead, as it is suggested by the Laravel creators.


public function store(Request $request){
  $request->validate([
    'name' => ['required', 'string', 'min:0', 'max:255'],
  ]);

  $name = $request->get('name', 'Something here so if its not defined you can handle it, but will more likely be defined, because in the validate method we have required for this field :), but just should you know, it can also be null or empty');
}

Your second suggestions is called magic properties in laravel, and yeah you can do it too, but remember you should ALWAYS validate your request data first before using it, you cannot possibly trust your users after all.

  • Related