data insert in many to many in laravel code example

Example 1: laravel many to many insert data

$user = User::find(2);   
$roleIds = [1, 2];
$user->roles()->attach($roleIds);

$user = User::find(3);   
$roleIds = [1, 2];
$user->roles()->sync($roleIds);

Example 2: add data one to many laravel

$employee = employee::find(1);

$salary1 = new Salary;
$salary->amount = '123456789';
$salary->payment_date = '15/07/2020';

$salary2 = new Salary;
$salary->amount = '123456789';
$salary->payment_date = '16/07/2020';

$employee = $employee->salary()->saveMany([$salary1, $salary2]);

Tags:

Php Example