Laravel 类型提示,id return 模型保存时为空

Laravel type hinting, id return null on model save

我正在尝试使用类型提示来存储值。

public function store(Model $model, ModelRequest $request) {
    $model->create($request->validated())->save();
    dd($model->id);
}

但是,Id 正在返回 null。

正如@aimme 在评论中所说,您不需要 save() 方法。 save() 方法 return truefalse.

如果您确实需要查看附加内容:

$new_created= $model->create($request->validated());
dd($new_created->id);

如果它不起作用那么你必须检查 $request->validated() 的 return:

dd($request->validated());

您实际上不能将 implicit route model binding 用于存储方法,因为您无法通过尚不存在的 ID 访问模型(因此没有 ID)。来自官方文档:

Laravel will automatically inject the model instance that has an ID matching the corresponding value from the request URI.

因此您必须手动创建模型,例如像这样

 public function store(StoreUserRequest $request) {
    $user = User::create($request->all());
 }