Search code examples
laravellaravel-nova

Populating $attributes with values from the previous model?


I've got a Laravel project (actually a Laravel Nova project) that involves entering a lot of data. To save some time I'd like to pre-fill some of the fields in my form, based on the logged in user's last entry.

I can pre-fill fields via the $attributes variable on my model, called Product, like so:

protected $attributes = [
  'category' => 'ABC'
];

And I can do this for more dynamic data in the constructor like so:

function __construct() {
  $this->attributes['category'] = Str::random();
  parent::__construct();
}

But I'm not quite sure how I'd go about this when I want to retrieve what the user entered last time. For example, I'd like to do this:

function __construct() {
  $user = auth()->user()->id;
  $last = Product::where('created_by', $user)->latest()->first();
  $this->attributes['category'] = $last['category'] ?? null;
}

However that ends up in an infinite loop. Same if I call $this->where('created_by' ...

Is there a way I can set $attributes of a new Product based on the last Product created by the user?


Solution

  • I found the solution in the Nova Defaultable package.

    Once you add the necessary traits, you can just add ->defaultLast() to a resource field and it'll default to the last set value. This also works for relationships which is perfect for my use case.