Update validation on laravel

0

I have a problem to do validation in the update in Laravel.

My Controller looks like this:

public function editar(EspecieRequest $request, Especie $esp)
{
    $especie = Especie::find($esp->id_especie);
    $valores = Request::all();
    $especie->fill($valores)->save();

    return redirect()->action('EspecieController@lista');
}

My Request looks like this:

    public function messages()
    {
        return [
            'nome_especie.required' => 'O campo nome é necessário'. $this->id_especie,
...
        ];
    }

The error that laravel shows is this: "Call to a member function fill () on null"

    
asked by anonymous 15.11.2017 / 21:57

1 answer

0

This error is caused when you use the find function and it does not find any matching results in the database for ID of Model searched.

In such cases, I usually use findOrFail to avoid this kind of problem.

Example:

 $especie = Especie::findOrFail($request->id_especie);

If the result for id_especie is not found in the database, an exception called ModelNotFoundException will be thrown.

It is also a good way to prevent your code from continuing to run unexpectedly if the result is not returned.

In your code there is something that does not seem to make much sense: Are you getting Especie $esp as a parameter, but are you looking for it again in the database through another query?

If you are binding the object Especie through the routes, you may need to change your code just for this:

public function editar(EspecieRequest $request, Especie $esp)
{

    $valores = Request::all();

    $esp->fill($valores)->save();

    return redirect()->action('EspecieController@lista');
}
    
16.11.2017 / 16:40