Laravel – Set data to null before deleting column from other table

  laravel, php, phpmyadmin

I have 2 tables. (1) being users, and (2) being foods.

In the [users] table, there is a food_id bracket that is linked as a foreign key to an item/column’s id in the other table [foods].

I am able to make a reservation of a [food] column, although I want to be able to press a ‘confirm’ button on the item once reserved, which will delete the item’s targetted column in the Database.

Although since both tables are linked with a foreign key, I know that I need to set the parent key to null in order to be able to fully delete the target column. Otherwise it throws me an error that I can’t delete/update a parent item with children objects.

(my food’s object primary ID being linked to the authenticated user’s food_id foreign key.)

This current code I tried only throws me the following error: "Call to a member function onDelete() on null"

$foodsId = User::find(auth()->user()->foods_id);
        $foodsId->onDelete('set null');
        $foodsId->save();

        $foodDel = Foods::find($id);
        $foodDel->delete();

Don’t exactly know what to think here.

Source: Laravel

Leave a Reply