2

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' ];
}
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
Joe
  • 15,669
  • 4
  • 48
  • 83

1 Answers1

3

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.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • Makes sense; I was kind of hoping for a different way of mapping them but it's not the end of the world :-) I agree that the `app()->make` is much less readable, cheers for the reply – Joe Dec 22 '16 at 08:47