Home > Mobile >  Laravel - Set data to null before deleting column from other table
Laravel - Set data to null before deleting column from other table

Time:10-14

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.

CodePudding user response:

You could edit the foreign key constraint to do this automatically, but what you're trying to do can be done with these lines.

$food = Food::findOrFail(auth()->user()->food_id);
auth()->user()->fill(['food_id' => null])->save(); // use forceFill() if food_id is not in the User's fillable fields.
$food->delete();

To have this happen automatically, you could make a migration with the command

php artisan make:migration changeFoodIdForeignKeyConstraint --table=users

function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropForeign(['food_id']);

        $table->foreign('food_id')
              ->references('id')->on('foods')
              ->onUpdate('cascade')
              ->onDelete('set null');
    });
}

Another option is to use a model event on the Food model

class Food extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::deleting(function ($food) {
            User::where('food_id', $food->id)->update(['food_id' => null]);
        });
    }

CodePudding user response:

Actually have found my own solution. I went to directly target my first foreign key, to then asign a null parameter to it, THEN fetch the targetted ID of my item and delete its column.

$user = auth()->user();
        $user->food_id = null;


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