chrisgrim's avatar

Laravel Delete All Related Rows not working

Hi, I have been looking up how to delete related rows and I am struggling to get it working. I have models Show and Tickets. I want to delete all tickets associated with shows when I delete a show. In my method I have

$event->shows()->whereNotIn('date', $request->dates)->delete();

and in my Show.php file I have

public function delete()
    {
      $this->tickets()->delete();
      return parent::delete();
    }

The show is deleted but the tickets still remain. The only thing I can think is that it is because I am calling the delete on $event->shows? If so, would I need to put the delete function on my Event.php file?

0 likes
9 replies
chrisgrim's avatar

I am doing soft deletes so I didn't know if I had to setup cascade on delete in my migration table

chrisgrim's avatar

Hi @jlrdw That tool looks perfect. I am worried about being dependant on too many plugins though. From what I see online this should be a relatively simple thing to code. If I use that tool then I am stuck further down the line if it breaks.

chrisgrim's avatar

Ok I gave that a shot what snapey suggested

class Event extends Model
{
    use Searchable, Favoritable, SoftDeletes;

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

        self::deleting(function (Event $event) {

            foreach ($event->shows as $show)
            {
                $show->delete();
            }
        });
    }
class Show extends Model
{
    use SoftDeletes;

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

        self::deleting(function (Show $show) {

            foreach ($show->tickets as $ticket)
            {
                $ticket->delete();
            }
        });
    }

and then in my method

$event->shows()->whereNotIn('date', $request->dates)->delete();

but it still only deletes the show and not the associated tickets. Do you see anything missing?

chrisgrim's avatar

I tried setting up an observer model just now and it still isn't deleting. In ShowObserver.php

use App\Show;

class ShowObserver
{

public function deleted(Show $show)
    {
        foreach ($show->tickets as $ticket)
            {
                $ticket->delete();
            }
    }

In my appserviceprovider

use App\Show;
use App\Observers\ShowObserver;
use Illuminate\Support\ServiceProvider;

   public function boot()
    {
        Show::observe(ShowObserver::class);
    }
chrisgrim's avatar
chrisgrim
OP
Best Answer
Level 10

I was able to get it working by adding this to my method

        $showDelete = $event->shows()->whereNotIn('date', $request->dates)->get();
        foreach($showDelete as $show){
            $show->tickets()->delete();
        }
        $event->shows()->whereNotIn('date', $request->dates)->delete();

It's not the cleanest but it works.

Please or to participate in this conversation.