Put error message in the view Laravel 5.6

1

Good evening guys. I am having difficulty returning a friendly error message to the user if he tries to register an employee with an email that is already saved in the database, since in my table this attribute was "set" as unique

Can anyone tell me how I can customize this in Laravel 5.6? currently is returning the default error message that is this here:

Illuminate \ Database \ QueryException (23000)

SQLSTATE [23000]: Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'funcion_email_functions_unique'

I would like to put a message in the view itself for the user, like this:

"Email already registered in the database!"

The exception path is this one:

.. vendor \ laravel \ framework \ src \ Illuminate \ Database \ Connection.php

And this is the exception handling:

 protected function runQueryCallback($query, $bindings, Closure $callback)
    {
        // To execute the statement, we'll simply call the callback, which will actually
        // run the SQL against the PDO connection. Then we can calculate the time it
        // took to execute and log the query SQL, bindings and time in our memory.
        try {
            $result = $callback($query, $bindings);
        }

        // If an exception occurs when attempting to run a query, we'll format the error
        // message to include the bindings with SQL, which will make this exception a
        // lot more helpful to the developer instead of just the database's errors.
        catch (Exception $e) {

            throw new QueryException(
                $query, $this->prepareBindings($bindings), $e
            );
        }

        return $result;
    }
    
asked by anonymous 09.09.2018 / 23:39

1 answer

3

Beast, the ideal is to do a validation before persisting the data.

In Laravel it is very simple, you can create a custom request or make the validation in the controller itself.

link

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'email' => 'required|email|unique:funcionario,email',
    ]);

    if ($validator->fails()) {
        return redirect('funcionario/create')
                        ->withErrors($validator)
                        ->withInput();
    }

    // continua e persiste os dados
    Funcionario::create($request->all());

    return redirect('funcionario/create')
    ->with('mensagem', 'Funcionário salvo com sucesso');
}
    
10.09.2018 / 01:31