Home > Enterprise >  Laravel what a diffrent betwenn $request->name and request('name')
Laravel what a diffrent betwenn $request->name and request('name')

Time:04-26

I have question about Request, what the best use?

$request->name 

or

request('name') 

what a diffrents?

CodePudding user response:

The $request is called dependency injection. the request() is a helper function for Request class from Illuminate\Http\Request. It's like Auth::user() and auth()->user() (not all Classes has helper functions).

There's no best use because they both have same function, to process a request from a client. In the other hand, You can inject a custom form request class to encapsulate the validation process in case client submit a form.

Something like this

public function store(StoreRequest $request) {
// Will process the request and return array. It will redirects to previous link if error happens
  $validated = $request->validated(); 
}

Docs

CodePudding user response:

You may want to use injected $request variable if you are using dedicated request class that validates your inputs, else you can use both of them.

You can use request helper everywhere in your project but for request variable you have to inject it to your function.

You better use request variable for consistency because you most probably need validation and have to use request variable.

  • Related