Problem deleting relational data

0

Gale need to delete cascading data, deleting the record from the users table is not deleting data from the documents table

Migration users:

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name', 70);
        $table->date('data_nascimento')->nullable();
        $table->string('sexo', 9)->nullable();
        $table->string('email')->unique();
        $table->string('nome_mae')->nullable();
        $table->string('foto_perfil', 180)->nullable();
        $table->string('tipo_pessoa', 40);
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
        $table->softDeletes();
    });
}

Migration document:

Schema::create('documentos', function (Blueprint $table) {
        $table->increments('id');
        $table->string('cpf', 15)->nullable();
        $table->string('rg', 30)->nullable();
        $table->date('data_expedicao_rg')->nullable();
        $table->string('orgao_emissor_rg', 50)->nullable();
        $table->string('cnpj', 20)->nullable();
        $table->string('ie', 30)->nullable();
        $table->string('sus', 50)->nullable();
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->on('id')->references('documentos')->onDelete('cascade');
        $table->timestamps();
        $table->softDeletes();
    });

Model User:

class User extends Authenticatable
{

    use Notifiable;
    use SoftDeletes;
    protected $table = 'users';

    public function documento()
    {
        return $this->hasMany('App\Models\Painel\Documento', 'user_id');
    }
}

Model document:

class Documento extends Model
{
    use SoftDeletes;
    protected $table = 'documentos';

    public function user()
    {
        return $this->belongsTo('App\User', 'user_id');
    }
}
    
asked by anonymous 20.02.2018 / 21:42

1 answer

0

Try adding your User class the following method:

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

    static::deleting(function($user) {
        $user->documento()->delete();
    });
}

There is also a cascade soft-dele lib, so if you are interested you can take a look at this link:

link

    
21.02.2018 / 16:07