Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Delete if no relationship exists

Below is the one of the model. I would like to delete a Telco entry only if no other model is referencing it? What is the best method?

namespace App;

use Illuminate\Database\Eloquent\Model;

class Telco extends Model
{
    public function operators()
    {
        return $this->hasMany('App\Operator');
    }

    public function packages()
    {
        return $this->hasMany('App\Package');
    }

    public function topups()
    {
        return $this->hasMany('App\Topup');
    }

    public function users()
    {
        return $this->morphMany('App\User', 'owner');
    }

    public function subscribers()
    {
        return $this->hasManyThrough('App\Subscriber', 'App\Operator');
    }
}
like image 384
Mohammad Avatar asked Sep 04 '17 09:09

Mohammad


People also ask

How to delete relation data in laravel?

To delete a model directly, call delete() on it and don't define a deleting listener in its boot method or define an empty deleting method. If you want to further delete relations of a related model, you will define a deleting listener in the boot method of that model and delete the relations there.

How to delete model from laravel?

Laravel Eloquent Deleting You can delete data after writing it to the database. You can either delete a model instance if you have retrieved one, or specify conditions for which records to delete. To delete a model instance, retrieve it and call the delete() method: $user = User::find(1); $user->delete();

What is Cascade on Delete laravel?

Laravel Soft Cascade is a package that makes it easy to perform soft cascade deletes and restores on related models using soft deleting.


1 Answers

You can use deleting model event and check if there any related records before deletion and prevent deletion if any exists.

In your Telco model

protected static function boot()
{
    parent::boot();

    static::deleting(function($telco) {
        $relationMethods = ['operators', 'packages', 'topups', 'users'];

        foreach ($relationMethods as $relationMethod) {
            if ($telco->$relationMethod()->count() > 0) {
                return false;
            }
        }
    });
}
like image 66
chanafdo Avatar answered Nov 15 '22 08:11

chanafdo