Can I refactor out an "unused" $request variable in a controller?

519 views Asked by At

Let's say I'm building a small application, where a small part of it is responsible for sending an email when a contact form is submitted. I only want to do that if the contact form passes some simple validation.

In the following controller the ContactRequest $request parameter is unused inside the method, although Laravel used the type-hinting to automatically apply the ContactRequest logic to the request.

Is it possible to achieve the same thing without leaving an unused variable in the controller method?


// Route
Route::post( 'contact', 'PageController@submitContactForm' );

// PageController
public function submitContactForm( ContactRequest $request ) {
    sendContactFormEmail();

    return redirect()->back();
}

// ContactRequest
public function authorize() {
    return hasNotSubmittedContactFormRecently();
}

public function rules() {
    return [ 'message' => 'required' ];
}
1

There are 1 answers

1
Marcin Nabiałek On BEST ANSWER

Yes, you can write your controller method like so:

// PageController
public function submitContactForm() 
{
    app()->make(ContactRequest::class);

    sendContactFormEmail();

    return redirect()->back();
}

and it will have same effect. However for me it's better to use it as you used it before.

Also probably you somehow use data you receive, so it might be more reasonable to use it like this:

sendContactFormEmail($request);

instead of probably injecting request into sendContactFormEmail method.