dimanche 4 septembre 2016

Larval Integrity constraint error not returning JSON in controller.

I'm in the process of learning Laravel to create a restful API. The following code is currently talking to the Users table and creating new records in it. However, when a duplicate email request hits the DB, the exception that I thought would be caught (to return a JSON error) is not, and I get a Laravel exception instead which appears to be a 'QueryException' that is deeper down within the app.

The message is as follows:

QueryException in Connection.php line 761:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'email' in ....

How do I best catch this error in my application and return a Json response as opposed to a Laravel one? am I missing something obvious?

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\User as User;
use JWTAuth;
use Response;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
  public function __construct(Request $request){
        $this->request = $request;
  }

  public function signup()
  {
    $email = $this->request->input('email');
    $password = $this->request->input('password');
    $credentials['email'] = $email;
    $credentials['password'] = $password;
    $credentials['name'] = 'Name';

    try {
         $user = User::create($credentials);
    } catch (Exception $e) {
        return Response::json(['error' => 'User already exists.'], HttpResponse::HTTP_CONFLICT);
    }

    $token = JWTAuth::fromUser($user);
    return Response::json(compact('token'));
  }


}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire