Reputation: 473
i am programming laravel app that has three tables
and coupons has category_id , company_id for relationship the thing is when i delete category i want to set in coupons table the category_id to null instead of leaving it there because leaving it will cause problems i saw foreigen keys and onDelete but i can't seem to understand it i will share migration and delete method
coupon migration
$table->id();
$table->string('title');
$table->string('link');
$table->longText('terms');
$table->string('show_image');
$table->string('coupon_code');
$table->tinyinteger('special');
$table->integer('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');;
$table->integer('company_id');
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');;
$table->timestamps();
about the other tables they only have title , image , id so no need to share them
Category Delete function
public function destroy(Request $request , $id)
{
$destroy_category = Categories::find($id);
//delete the icon
$icon = $destroy_category->icon;
File::delete(public_path($icon));
$destroy_category->delete();
return redirect('/category/index')->with('success' , 'Category Deleted Successfully');
}
please show me how i should set the category_id to null or do something about it
Thanks in advance
Upvotes: 0
Views: 349
Reputation: 961
Do the following:
php artisan make:observer CategoryObserver
app/Observers/CategoryObserver.php
deleting()
method, put this: //delete the icon
$icon = $destroy_category->icon;
File::delete(public_path($icon));
$destroy_category->delete();
app/Provivers/AppServiceProvider.php
and place this in the boot()
method:Category::observe(CategoryObserver::class); //import the class correctly
public function destroy(Request $request , $id)
{
$destroy_category = Categories::find($id);
$destroy_category->delete(); //this will fire the CategoryObserver::deleting() method
return redirect('/category/index')->with('success' , 'Category Deleted Successfully');
}
Upvotes: 1