To set the itemtype_id for all related items to a default value of 1 ("Unassigned") on delete of the foreign key in the ItemTypes table, you can use a combination of database constraints and model observers.
First, modify your migration to set the itemtype_id column to nullable and add a default value of 1:
public function up(): void
{
Schema::create('items', function (Blueprint $table) {
$table->id();
$table->foreignId('itemtype_id')->nullable()->default(1)->constrained();
$table->string('description');
$table->string('color')->nullable();
$table->string('material')->nullable();
$table->timestamps();
});
}
Next, create a model observer for the Item model. In the observer's deleting method, you can update the related items' itemtype_id to the default value of 1:
namespace App\Observers;
use App\Models\Item;
class ItemObserver
{
public function deleting(Item $item)
{
$item->items()->update(['itemtype_id' => 1]);
}
}
Don't forget to register the observer in the boot method of your AppServiceProvider or any other service provider:
use App\Models\Item;
use App\Observers\ItemObserver;
public function boot()
{
Item::observe(ItemObserver::class);
}
With this setup, whenever a foreign key in the ItemTypes table is deleted, the deleting method in the ItemObserver will be triggered, and it will update the related items' itemtype_id to the default value of 1.
Note: Make sure to replace App\Models\Item with the actual namespace and class name of your Item model.