Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

laravel delete records of child relations

 <?php

        class User extends Eloquent
        {
            // this will enable soft delete on model.
            use SoftDeletingTrait;
            protected $dates = ['deleted_at'];

            public function photos()
            {
                return $this->has_many('Photo');
            }

            // override existing delete method.
            // invoke when we call $user->delete(), softdelete.
            public function delete()
            {
                // delete all associated photos
                $this->photos()->delete();

                // delete the user
                return parent::delete();
            }

            // override existing forceDelete method.
            // invoke when we call $user->forceDelete(), force delete
            public function forceDelete()
            {
                // use of withTrashed() to delete all records
                $this->photos()->withTrashed()->forceDelete();

                // delete the user
                return parent::forceDelete();
            }
    }
 
PREVIOUS NEXT
Tagged: #laravel #delete #records #child #relations
ADD COMMENT
Topic
Name
8+9 =