获取Laravel模型-> save()错误代码或消息

时间:2019-08-27 03:24:33

标签: php mysql laravel error-handling eloquent

laravel Model->save()不会引发数据库异常,我想检查列的唯一约束(没有主键或其他外键)。

Model->save()返回false时,有什么方法可以获取消息的数据库错误代码吗?

3 个答案:

答案 0 :(得分:1)

您可以尝试QueryException。捕获任何SQL语法或查询错误。

use Illuminate\Database\QueryException

try {

        $model = Model::find($id);
        $model->name = 'joe';
        $model->save();

    } catch (QueryException $e) {

        dd($e->getMessage());

    }

答案 1 :(得分:0)

您可以在数据库中使用“ UNIQUE”列,然后通过QueryException处理错误。

答案 2 :(得分:0)

=> If you have label exists, See below error:
  "Exception message:SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'TEST  GO' for key 'materials_label_unique' (SQL: insert into `materials` (`label`, `updated_at`, `created_at`) values (TEST GO, 2019-08-27 09:53:47, 2019-08-27 09:53:47)) with code: 23000"

function insertMaterial()
{
    try {
        $material = new Materials;
        $material->label = "TEST GO";
        if( $material->save() ) {
            return "True as a string";
        } else {
            return "False as a string";
        }
    } catch (\Exception $e) {
        return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
    }
}


=> If you'll try to find the non-existing record, See below error:
   "Exception message: Creating default object from the empty value with code: 0"

function insertMaterial()
{
    try {
        $material = Materials::find(1111);
        $material->label = "TEST GO";
        if( $material->save() ) {
            return "True as a String";
        } else {
            return "False as a String";
        }
    } catch (\Exception $e) {
        return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
    }
}