【问题标题】:Laravel: How can I show error message using query builderLaravel:如何使用查询生成器显示错误消息
【发布时间】:2021-09-17 16:42:23
【问题描述】:

我想用这个查询生成器更新我的表中的一行。

$new_item = DB::table('peminjams')
            ->where('id', $dipinjam->id_peminjam)
            ->update([
                 'nama' => $request->nama,
                 'cp' => $request->cp,
                 'jaminan' => $request->jaminan
             ]);

当我dd($new_item)它返回false时,该项目没有更新。

我仍然不知道为什么它失败了,因为它只给出一个布尔值。

【问题讨论】:

  • 尝试调试您的代码。首先检查->where('id', $dipinjam->id_peminjam)->first()是否返回任何值。然后检查请求值。
  • try dd($dipinjam->id_peminjam) 是否可以返回任何值
  • 确保您的模型的这些属性不在$guarded 属性中,因为如果它们是,它们将不会是大量assignable。或者,如果您改用 $fillable,请确保这些属性在其中。

标签: php laravel


【解决方案1】:
try {
        // Validate the value...
    } catch (Exception $e) {
        echo $exception->getMessage();exit;

    }

if ($exception instanceof \HttpException || $exception instanceof \ErrorException) {

                $exceptionArry = [
                    'file'    => $exception->getFile(),
                    'code'    => $exception->getCode(),
                    'line'    => $exception->getLine(),
                    'message' => $exception->getMessage(),
                ];
                dd($exceptionArry);
            }

https://laravel.com/docs/5.8/errors

【讨论】:

    【解决方案2】:

    首先,我们检查first() 方法的返回值。如果返回值为null,则返回false。

    $new_item = DB::table('peminjams')->where('id', $dipinjam->id_peminjam)->first();
    
    if(is_null($new_item)) {
        return false;
    } else {
        DB::table('peminjams')
            ->where('id', $dipinjam->id_peminjam)
            ->update([
                'nama' => $request->nama,
                'cp' => $request->cp,
                'jaminan' => $request->jaminan
            ]);
    }
    

    使用雄辩

    $new_item = Peminjams::findOrFail($dipinjam->id_peminjam);
    
    $new_item->nama = $request->nama;
    $new_item->cp = $request->cp;
    $new_item->jaminan = $request->jaminan;
    $new_item->update();
    

    【讨论】:

      猜你喜欢
      • 2019-02-14
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 2018-12-05
      相关资源
      最近更新 更多