Laravel Model Error Handling when Creating Laravel Model Error Handling when Creating laravel laravel

Laravel Model Error Handling when Creating


Just wrap that code in a try-catch block. Something like this:

try {    MFUser::create(array(        'user_reference' => $this->userReference,        'first_name' => $this->firstName,        'last_name' => $this->lastName,        'user_type_id' => $this->userTypeId,        'email' => $this->email,        'password' => $this->password    ));} catch (\Illuminate\Database\QueryException $exception) {    // You can check get the details of the error using `errorInfo`:    $errorInfo = $exception->errorInfo;    // Return the response to the client..}


I prefer to reserve try/catch's for unexpected events that can't be handled elsewhere. In this case, you can utilise validation as a first measure, and the exception handler as a backup measure.

If the form request fails, the error messages are flashed and the user is returned to the previous page (where the form was submitted) and you can handle the messages gracefully. Validation requests

// First line of defence - gracefully handle// Controller public function store(MFUserRequest $request){    // The incoming request is valid...    MFUser::create(array(...));}// Form Requestclass MFUserRequest extends Request {    public function rules()    {        return [            'email' => 'required|email|unique:users,email',        ];    }    }

Elsewhere, in your App\Exceptions directory you have the exception handler class that can be a catch all for various errors. Use this, when you haven't been able to gracefully handle it further down.

// Second line of defence - something was missed, and a model was  // created without going via the above form requestnamespace App\Exceptions;class Handler extends ExceptionHandler{    public function render($request, Exception $e)    {                if($e instanceof QueryException) {            // log it or similar. then dump them back on the dashboard or general something bad            // has happened screen            return redirect()->route('/dashboard');        }    }}


Simply make use of try / catch block.

use Illuminate\Database\QueryException;// ...try {    // DB query goes here.} catch (QueryException $e) {    // Logics in case there are QueryException goes here}// ...