php – Laravel sync hasMany with belongsTo array-ThrowExceptions

Exception or error:

Kind time of day everyone! The essence of my problem is this:
there are two models Contact and PhoneNum! relationships in models:

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    protected $table = 'contacts';
    public function phoneNums()
    {
        return $this->hasMany('App\Models\PhoneNum');
    }
}

PhoneNum model

class PhoneNum extends Model
{
    protected $table = 'phoneNums';
    protected $fillable = ['phone_num'];

    public function contact()
    {
        return $this->belongsTo('App\Models\Contact');
    }
}

In the form of editing contact, I get its name and an array with the phone numbers of this contact.

ContactController

public function update(Request $request, $id)
{
    $contact = Contact::find($id);
    $contact->name = $request->name;
    $contact->save();

    //what should I do with the array $request->phoneNums ????

    return redirect('/');
}

I can not synchronize these new phone numbers with a contact on id. Can you help me with this?

How to solve:

First of all: change $request->name to $request->input('name'). With this change you’ll know in about 5 months that this variable is coming from a form.

Second, the solutions to your problem. This is an example. You need to change it to the right names and add the variable to the mass assignment field in the model.

foreach($request->input('phoneNums') as $phoneNumber){
    $contact->phoneNums()->create([
        'number' => $phoneNumber
    ]);
}

And take a look at the PSR rules, so you can make your code more read-friendly: http://www.php-fig.org/psr/.

Answer:

You must remove old contacts first and then insert the newly created.

$contact->phoneNums()->delete();
$contact->phoneNums()->saveMany([$request->input('phoneNums')]);

Answer:

Add sync method to update function as below

Public function update(Request $request, $id)

{
    $contact = Contact::find($id);
    $contact->name = $request->name;
    $contact->save();
    $contact->phoneNums()->sync($request->phoneNums, true)

    return redirect('/');
} 

Leave a Reply

Your email address will not be published. Required fields are marked *