Home > Enterprise >  Can't insert array with a variable in Laravel Controller
Can't insert array with a variable in Laravel Controller

Time:05-02

I'm trying to insert an array in my database with a variable member_id.

HTML

My Controller

This work without member_id

 foreach ($request->moreFields as $key => $value) {
                Permit::create($value);
  }

This doesn't work with member id

foreach ($request->moreFields as $key => $value) {
            Permit::create([    
                'member_id' => $member_id,
                'license_type' => $request->license_type[$i],
                'license_number' => $request->license_number[$i],
                'registration_date' => $request->registration_date[$i],
                'expiration_date' => $request->expiration_date[$i],
            ]);
        }

I'm trying to insert an array with a variable so that it can have relationships in the member's table

CodePudding user response:

You can just modify the array before insert it to Database like array_merge(),

foreach ($request->moreFields as $key => $value) {
    Permit::create(array_merge($value, ['member_id' => $member_id]));
}

CodePudding user response:

I can't see the rest of the code to be sure but my guess is you're using a closure which removes $member_id form the scope of your loop. If that's the case, then the use keyword will allow you to access variables outside of the scope of the closure. For example -

function () use ($member_id) { // pass $member_id into scope of closure
    foreach ($request->moreFields as $key => $value) {
        Permit::create([    
            'member_id' => $member_id,
            'license_type' => $request->license_type[$i],
            'license_number' => $request->license_number[$i],
            'registration_date' => $request->registration_date[$i],
            'expiration_date' => $request->expiration_date[$i],
        ]);
    }
};
  • Related