2
votes

Call to undefined method Illuminate\Database\Query\Builder::contains()

Here are my models:

DepartCity.php

class DepartCity extends Eloquent {
protected $guarded = array();

public static $rules = array();

public function countries() {
    return $this->belongsToMany('Country', 'depart_cities_countries', 'depcity_id',     'country_id');
}

public $timestamps = false;

}

Country.php

class Country extends Eloquent {
protected $guarded = array();

public static $rules = array();

public function depart_cities() {
    return $this->belongsToMany('DepartCity', 'depart_cities_countries', 'country_id', 'depcity_id');
}

public function resorts() {
    return $this->hasMany('Resort');
}

public $timestamps = false;
}

Here is part of my code:

        $dep_cities = DepartCity::all(); 
    foreach ($dep_cities as $sletat_city) {
        $countries = $swc->getCountries($sletat_city->sletat_id)->GetCountriesResult->Country;
        foreach ($countries as $sletat_country) {
            $sletat_country_id = $sletat_country->Id;
            $country = (Country::where(array ('sletat_id' => $sletat_country_id))->first());
            if (!$country) {
                $country = new Country;
                $country->sletat_id = $sletat_country_id;
            }
            $country->name = $sletat_country->Name;
            $country->save();

            if (!($country->depart_cities()->contains($sletat_city->Id))) {
                $country->depart_cities()->save($sletat_city);
            } 
        }
    }

Getting error here:

(!($country->depart_cities()->contains($sletat_city->Id)))

Type of class $country->depart_cities() is Illuminate\Database\Eloquent\Relations\BelongsToMany and there is no method "contains" but I cant understand how to do it works

Please help me with it :)

1
(!($country->depart_cities->contains($sletat_city->Id))) i removed the () after depart cities. - Matt Burrow
still not woking: "Call to a member function contains() on a non-object" - user3828730
change $country to $country = (Country::with('depart_cities')->where(array ('sletat_id' => $sletat_country_id))->first()); - Matt Burrow
nice, thanks, it works - user3828730
Added as an answer :) @user3828730 - Matt Burrow

1 Answers

3
votes

Change the following;

 $country = (Country::with('depart_cities')->where(array ('sletat_id' => $sletat_country_id))->first());

and

 if (!($country->depart_cities->contains($sletat_city->Id))) {
       $country->depart_cities()->save($sletat_city);
 }