Michael Anaman
Michael Anaman

Reputation: 199

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

Below is my model displayed , my controller and view. I am trying to save contacts to a particular group. When i do save i get the error

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

But then, i cannot find any error in my model neither in my controller as well. What could i be doing wrong here?

PS: Beginner in laravel

Group

public function contacts()
    {
        return $this->hasMany('App\Contact');
        // ->withTimestamps();
    }

Contact

 public function groups()
    {
        return $this->belongsTo('App\Group');
        // ->withTimestamps();
    }

    public function saveGroup($groups)
    {
        if(!empty($groups))
        {
            $this->groups()->sync($groups);
        } else {
            $this->groups()->detach();
        }
    }

Controller

 public function store(Request $request)
        {
            $contact = new Contact(array(
                'name'  => $request->get('name'),

            ));
            $customer->groups()->sync($request->get('group[]'));

            $contact->save();
        }

View

 <div class="input-field col s12">
<select  class="form-control" id="group" name="group[]" mulitple>
@foreach($groups as $group)
<option value="{!! $group->id !!}" @if(in_array($group->id, $selectedGroups)) selected="selected" @endif >
               {!! $group->title !!}
</option>
    @endforeach
</select>
          </div>

Upvotes: 2

Views: 1679

Answers (1)

Adrian Hernandez-Lopez
Adrian Hernandez-Lopez

Reputation: 553

Sync function is related to one-to-many or many-to-many relationships. See https://laravel.com/docs/5.6/eloquent-relationships#updating-many-to-many-relationships for more info.

I'd suggest you to change your model code to something like

public function groups()
{
    return $this->belongsToMany('App\Group');
    // ->withTimestamps();
}

public function saveGroup($groups)
{
    if(!empty($groups))
    {
        $this->groups()->sync($groups);
    } else {
        $this->groups()->detach();
    }
}

Upvotes: 1

Related Questions