Laravel contact form is not working correctly

I have a problem with the Laravel site’s form, when I send the form through the site it shows an error, using devTools it is noted that it is an error 500 of the Post method, but the form is sent anyway.

the following error appears in the laravel log file

[2021-12-15 11:27:49] production.ERROR: Missing required parameters for [Route: contato] [URI: {lang}/contato]. {"exception":"[object] (Illuminate\Routing\Exceptions\UrlGenerationException(code: 0): Missing required parameters for [Route: contato] [URI: {lang}/contato]. at /home/corstonecom/public_html/vendor/laravel/framework/src/Illuminate/Routing/Exceptions/UrlGenerationException.php:17)

In the form view it like this:

<form id="frm-contato" class="site-form" action="{{ route('contato-enviar', app()->getLocale()) }}" method="post">

In the routes file web.php it like this:

Route::view('/contato', 'fale-conosco')->name('contato');

Route::post('/contato', 'HomeController@enviarContato')->name('contato-enviar');

and in the controller it like this:

public function enviarContato(EnviaContatoRequest $request)

{
    
    $inputs  = $request->all();

    $inputs['localidade'] = $inputs['cidade'] . '/' . $inputs['uf'];

    $contato = Contatos::create($inputs);



    Lead::fastSave([

        'name'  => $inputs['nome'],

        'email' => $inputs['email'],

    ]);



    Mail::send(new FaleConosco($contato));

    Session::flash('contato_enviado', 'sucesso');

    return redirect()->route('contato');
    

}

Where am i going wrong?

>Solution :

You would need to pass the lang parameter when calling the route method when doing the redirect in your Controller method as the route contato requires the lang parameter:

return redirect()->route('contato', ['lang' => app()->getLocale()]);

It is best to get in the habit of using an associative array for the parameters as any more than 1 parameter and they will need to be in an associative array for the URL generator to match them up.

If you don’t want to have to constantly be passing this app()->getLocale() value to the URL helpers you can set a default for the lang parameter and it will be added for you. You could use a middleware to do this. Example of the functionality of setting a default value for a parameter:

public function handle($request, $next)
{
    \URL::defaults([
        'lang' => app()->getLocale(),
    ]);

    return $next($request);
}

Now you don’t have to pass the parameter for lang when generating URLs as it has a default value set.

If you already have a "locale" middleware that is handling the locale you can add this to it.

Leave a Reply