Search code examples
laravellaravel-5.3dingo-api

Different error message if I include an exception in Request rules


I have the following update function for my model:

public function update(PartnerRequest $request, $id)
{
    $partner = Partner::findOrFail($id);

    if(!$partner -> update($request->all())) {
        throw new HttpException(500);
    }

    return response()->json([
            'status' => 'ok'
        ], 201);

}

And here is the request file:

namespace App\Api\V1\Requests;

use Config;
use Dingo\Api\Http\FormRequest;

class PartnerRequest extends FormRequest
{
    public function rules()
    {
        return [
               'name' => 'required|unique:partners,' . $this->id . ',id',
               'email' => 'email'    
        ];
    }

    public function authorize()
    {
        return true;
    }
}

If I remove the exception on the rule and make it as 'name' => 'required|unique:partners', I have the following error message in case of duplicate inputs:

{
  "error": {
    "message": "422 Unprocessable Entity",
    "errors": {
      "name": [
        "The name has already been taken."
      ]
    },
    "status_code": 422
  }
}

But the problem is on Patch, where I cannot update the model (due to the unique name rule). So, I need the exception. However, if I include it, instead of the above specific error, I have a generic one like this:

  "error": {
    "message": "SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: partners.name (SQL: update \"partners\" set \"name\" = test, \"updated_at\" = 2017-03-03 10:47:53 where \"id\" = 3)",
    "code": "23000",
    "status_code": 500
  }
}

Routes:

$api->post('partner/store', 'App\\Api\\V1\\Controllers\\PartnerController@store');
$api->get('partner/all', 'App\\Api\\V1\\Controllers\\PartnerController@index');
$api->get('partner/{id}', 'App\\Api\\V1\\Controllers\\PartnerController@show');
$api->patch('partner/{id}', 'App\\Api\\V1\\Controllers\\PartnerController@update');

Solution

  • You could try doing something like:

    public function rules()
    {
        switch ($this->method()) {
            case 'POST':
                return [
                    'name' => 'required|unique:partners',
                    'email' => 'email'
                ];
            case 'PUT':
            case 'PATCH':
    
            return [
                'name' => 'required|unique:partners,name,' . $this->route('id') . ',id',
                'email' => 'email'
            ];
        }
    }
    

    Hope this helps!