Laravel type hinting, id return null on model save

467 Views Asked by At

I am trying to use type hinting for storing the value.

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

But, Id is returning null.

2

There are 2 best solutions below

0
On BEST ANSWER

As said in comment by @aimme, you don't need save() methode. The save() methode return true or false.

If you realy need to see what appened:

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

if it not working then you have to check the return of $request->validated():

dd($request->validated());
0
On

You can't actually use the implicit route model binding for the store method, as you can't access a model by ID which does not exist yet (and hence has no ID). From the official docs:

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

So you would have to create the model manually for example like this

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