0

my name is andy and i'm new to Laravel, I would like to ask how to store my user id into the new table which table name ( company_policy_users ) by using looping method ? Can anyone help me out ? Thank you so much Here is my controller coding

foreach ($array as $selectedUser){
        $policyUser = new $policyUser([
            'policy' => $request->get('id'),
            'user_id' => $selectedUser,
            'read' => 0
        ]);
        $policyUser->save();

My database name = ( company_policy ) with table name - ( company_policy_users ) : The column we have inside the ( company_policy_users ) table 1. id = (bigint) 2. user_id = (int) 3. policy_id = (int) 4. read_by = ( Boolean ) 5. date_read = (datetime)

andy
  • 1
  • please can you edit your question and be more specific, so we can help? where are you performing the loop? you should post your blade, route and controller code – Buchi Feb 25 '20 at 02:47

1 Answers1

1

Let Define that your model like

CompanyPolicy
CompanyPolicyUser 

There are a lot of way to insert multi record. it would be better if you provide your view and controller code. But looking to your code I will using Model::insert($arrData);

$policyUsers = [];

foreach ($array as $selectedUser){
    $policyUsers[] = [
        'policy_id' => $request->id,
        'user_id' => $selectedUser,
        'read' => 0
    ];
}

if(count($policyUsers) > 0) {
    CompanyPolicyUser::insert($policyUsers);
}

Insert Multi Records

Thank and hope it can help.

Sok Hai
  • 546
  • 4
  • 12