Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Model Error Handling when Creating

Tags:

php

laravel

I want to use Eloquent to create a DB entry like this:

   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
    ));

It works well, except for the case, when exactly the same data is put into the fields, which is expected, as there should be no duplicate. I get the QueryExecption then.

But how do I properly perform error handling here to check if this query exception occurs so I can return a response from my server to the client via json then?

like image 267
sesc360 Avatar asked Mar 26 '16 23:03

sesc360


4 Answers

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..
}
like image 67
Luís Cruz Avatar answered Nov 12 '22 06:11

Luís Cruz


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 Request
class 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 request
namespace 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');
        }
    }
}
like image 23
Chris Avatar answered Nov 12 '22 06:11

Chris


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
}

// ...
like image 35
James Akwuh Avatar answered Nov 12 '22 08:11

James Akwuh


Try and Catch something might help u and imagine for create try catch for all of them, but have best practice to handle all of QueryException, my recommend is use Laravel Exceptions Handler because it's make u easy for make execption global!

let's try it!, open App\Exception\Handler.php and at render method u can write like this one

public function render($request, Throwable $exception)
{
   if ($request->ajax() || $request->wantsJson()) {
      if ($exception instanceof QueryException) {
          // example algo for make response
          return response()->json(['message' => 'xxx'], 403);
      }
   }

   return parent::render($request, $exception);
}

after that, u can get xxx json for every error request triggered by Query

like image 37
Abdul Aziz Al Basyir Avatar answered Nov 12 '22 08:11

Abdul Aziz Al Basyir