Laravel 5: cascade soft delete

I am having offers and services table.

Service(s) is a child of an offer. So far I have established functionality for soft deleting an offer. How would I also soft delete appended services? Here is my code:

Migration Offers

Schema::create('offers', function(Blueprint $table)
{
    $table->increments('id')->unsigned();
    ...    
    $table->timestamps();
    $table->softDeletes();
});

Migration Services

Schema::create('services', function(Blueprint $table) 
{
    $table->increments('id');
    $table->integer('offer_id')->unsigned();   
    ...
    $table->timestamps();
    $table->softDeletes();
});

Schema::table('services', function($table) 
{
    $table->foreign('offer_id')
          ->references('id')
          ->on('offers');
});

Model Offer

use SoftDeletes;
protected $dates = ['deleted_at'];

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

Model Service

public function offer() {
    return $this->belongsTo('App\Offer');
} 

Delete method

public function destroy($id)
{
    $offer = Offer::find($id);
    $offer->delete();
}

Thank you for all the help.

Answers


I have put this code in Offer model:

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

    static::deleting(function($offer) {
        $offer->services()->delete();
    });
}

And added missing

use SoftDeletes;
protected $dates = ['deleted_at'];

in the Service model.


You should use Eloquent events for this.

Offers::deleted(function($offer) {
    $offer->services()->delete();
});

Offers::restored(function($offer) {
    $offer->services()->withTrashed()->restore();
});

If you want to get cascading softDeletes in your Eloquent Models I highly recommend using this library iatstuti/laravel-cascade-soft-deletes

Composer

// get it with composer.
$ composer require iatstuti/laravel-cascade-soft-deletes="1.0.*"

Quick example

The one provided in the getting started sample.

<?php

namespace App;

use App\Comment;
use Iatstuti\Database\Support\CascadeSoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes, CascadeSoftDeletes;

    protected $cascadeDeletes = ['comments'];

    protected $dates = ['deleted_at'];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}  

You can do like this.

self::deleting(function($offer) {
    $offer->services()->delete();
});

self::restoring(function ($offer) {
   $offer->services()->restore();
});

You should first delete/restore the children records (services) before deleting/restoring the parent (offer). Failing to do this, will trigger referential integrity MySql error.


Need Your Help

iPhone - Remove status bar programmatically

iphone ios uiimagepickercontroller statusbar

I have made an app that implements the iPhone's camera.