0

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

2 Answers 2

2

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]));
}
Sign up to request clarification or add additional context in comments.

Comments

0

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],
        ]);
    }
};

3 Comments

\DB::transaction(function () use($request,$member_id, $license){ actually i have in db::transaction
i tried same as here positronx.io/… but want to add member_id
Then I guess member_id isn't returning anything, and if there are no errors then it's failing gracefully. If this is an AJAX call what is the response in dev tools? And how is member_id defined?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.