Validation of the update in the Standard

Asked

Viewed 637 times

0

I have a problem to validate the update on Laravel.

My Controller is 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 is like this:

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

The error that the Laravel shows is this: "Call to a Member Function Fill() on null"

  • Of a var_dump($esp);, may $esp is no value, or the variable $valores is receiving null.

  • have to check $especie if you returned any data

  • function editar(EspecieRequest $request, Especie $esp) That’s what’s weird ...!

  • The $esp had not I made in trial and error, I did the var_dump of $esp and $values and locked my pc, then I did a variable only, I do not remember which and I saw that left a junk memory in it

1 answer

1

This error is caused when you use the function find and it does not find any corresponding result in the database for the ID of Model researched.

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

Example:

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

If the result to id_especie is not found in the bank, an exception called ModelNotFoundException will be launched.

It’s even a good way, by the way, to prevent your code from running unexpectedly if the result is not returned.

In your code there is something that doesn’t seem to make much sense: You are receiving the Especie $esp as parameter, but is searching again in the database through another query?

If you are making bind of 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');
}
  • My original method did not have Especie $esp, I did in trial and error, the problem is that when it passes the request, the request does not return the values for update

  • @lipesmile, you gave a dd($request::all()), to know if the data is arrived? If it does not work, which I find difficult, change the function parameter to Request $request to make sure you are sending if still persists the problem there the error is probably how you are sending...

  • 1

    Shouldn’t be $request::all() instead of Request:all(), since $request is what is coming from the parameter?

  • Well noticed @Ricardolucas

Browser other questions tagged

You are not signed in. Login or sign up in order to post.