Laravel nova getting the ID value of the created model in the fillUsing callback of the field

Viewed 5088

I am developing a Web application using Laravel Nova. Laravel Nova is quite a new technology. Now, what I am doing now is overriding the Field callback to add own business logic rather than performing the database operation. See my scenario below.

This is my fields method of my resource

public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
            Text::make("Subject")->fillUsing(function(){
                //here, I like to get the id of the created model. How?
            }),
            Text::make('Title')->sortable()
        ];
    }

As you can see that I am overriding the logic of the Subject field. I like to fetch the Id of the model inside the callback. How can I achieve it?

1 Answers

When you take a look at the Field.php class, you will see this is how the fillCallback is used:

protected function fillAttribute(NovaRequest $request, $requestAttribute, $model, $attribute)
{
    if (isset($this->fillCallback)) {
        return call_user_func(
            $this->fillCallback, $request, $model, $attribute, $requestAttribute
        );
    }

    $this->fillAttributeFromRequest(
        $request, $requestAttribute, $model, $attribute
    );
}

Therefore, inside your callback function, you can access the variables like this:

Text::make('Subject')->fillUsing(function($request, $model, $attribute, $requestAttribute) {
    dd($model->id);
});
Related