【问题标题】:\Eloquent\Model::Create method returns null with status code OK\Eloquent\Model::Create 方法返回 null,状态码 OK
【发布时间】:2025-12-03 10:00:02
【问题描述】:

Create 方法无法按预期工作。始终返回 OK 状态,带有空数据并且在 db 中没有插入。不幸的是没有显示错误,所以我不知道该怎么办。

protected function addBooking(Request $request)
{

    $data = $request->all();


    if ($this->validator($data)->fails()) {
        return $this->sendError('Validation Error.', $this->validator($data)->errors());
    }

    Booking::create($data);

    return $data;

}

这是迁移

 public function up()
{
    Schema::create('bookings', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('booker_id')->nullable(false)->unsigned();
        $table->bigInteger('classroom_id')->nullable(false)->unsigned();
        $table->string('name');
        $table->string('color')->default("#ff0000");
        $table->string('file')->default(NULL);
        $table->string('start')->nullable(false);
        $table->string('end')->nullable(false);
        $table->timestamps();
        $table->foreign('booker_id')->references('id')->on('users');
        $table->foreign('classroom_id')->references('id')->on('classrooms');
    });
}

型号

  class Booking extends Model
    {
    protected $fillable = [
        'booker_id', 'classroom_id', 'name', 'color', 'file', 'start', 'end'
    ];

    protected $hidden = [
    ];

    protected $casts = [
    ];
}

我如何发送请求

{
  "booker_id": 10,
  "classroom_id": 4,
  "name": "Microsoft",
  "start": "2019-04-25 14:45",
  "end": "2019-04-25 16:45",
  "color": "#ff0000",
  "file": "test"
}

【问题讨论】:

  • 你能在Booking::create($data)之前试试dd($data)吗?
  • 如果它返回 null 那么 $data 为 null 因为你返回的是 $data 而不是 Booking::create($data) 所以我认为你可以在'return $data'之前中止请求以检查它是否甚至达到了这条线。
  • dd($data) 的输出太大,无法在此处发布
  • 你能用 request->only 代替 request->all 并返回 Booking::create($data);?
  • 是的,显然查看 laravel.log 确实有帮助。问题是Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails 这基本上意味着我很愚蠢。外键的值之一不存在。

标签: php laravel


【解决方案1】:

// 你应该使用表单请求来验证数据。并将您的所有业务逻辑转移到模型中

protected function addBooking(Request $request)
{

    $data = $request->all();


    if ($this->validator($data)->fails()) {
        return $this->sendError('Validation Error.', $this->validator($data)->errors());
    }

    return Booking::create($data)->fresh();

}

【讨论】:

    【解决方案2】:

    Laravel 有一个路由约定,如果你正在创建新项目,方法名应该是 store()。 我正在使用两种创建新元素的方法: 首先这更短,我在 StoreBooking 中添加验证

    public function store( StoreBooking $request ) {
      $data = $request->all();
      $booking = Booking::query()->create( $data );
    }
    

    基于 laravel 文档的记录器:

    public function store( StoreBooking $request ) {
     $booking = new Booking();
     $booking->bookier_id = $request->bookier_id;
     /**
      add other items
     **/
     $booking->save();
    }
    

    【讨论】: