Tuesday, February 28, 2017

Conditional detach in many to many relationship laravel

I have 2 models Tour.php

public function includes()
{
    return $this->belongsToMany('App\Included');
}

Included.php

public function tours()
{
    return $this->belongsToMany('App\Tour');
}

I'm trying to detach includeds if a tour has includeds in it while deleting a a tour.

Below code is what I have tried:

    public function destroy($id)
{
    $tour = Tour::find($id);

    if ($test = $tour->includeds()->count() != null) {
        $tour->includeds()->detach();
    }
    if ($test = $tour->excludeds()->count() != null) {
        $tour->excludeds()->detach();
    }        
    $tour->delete();

    Session::flash('success', 'The tour is sucessfully deleted.');
    return redirect()->route('tours.index');
}

The above code is generating Call to undefined method Illuminate\Database\Query\Builder::includeds() error. Please point out my mistake that i'm making.




via Tanja Forsberg

Advertisement