5

I am storing multiple values in Laravel. In the form, I have check box for each input and I want to store value if checkbox is checked for that input. The problem I am facing is no matter which checkbox I check, its always saving from first input value. If I check one option, it is storing first value. If I check 2 options, it is storing first and second values, and so on.

Here is the form for checkbox

<input type="checkbox" name="checked[]" value="{{ $employee->id }}">

The store method

public function store(Request $request)
    {
        foreach ($request->employee_id as $key => $val) {
            $payrolls = new Payroll;
            if (isset($request->checked[$key])) {
                $payrolls->basic = $request->basic[$key];
                $payrolls->employee_id = $val;
                $payrolls->save();
            }
        }

        return redirect('/');
    }
5
  • are you sure that the first value checked is false? Commented Mar 24, 2018 at 15:54
  • Yes, I have checked multiple times. Commented Mar 24, 2018 at 15:55
  • any JS involved? Commented Mar 24, 2018 at 15:58
  • not yet. I am preferring a php only solution Commented Mar 24, 2018 at 16:05
  • Use isset($request->get('checked')[$key]). Commented Mar 24, 2018 at 16:22

1 Answer 1

2

The method isset checking by the key, but in the array of checked you need to search by the value, use method in_array()

public function store(Request $request)
{
    foreach ($request->employee_id as $key => $val) {
        $payrolls = new Payroll;
        if (in_array($val, $request->checked)) {
            $payrolls->basic = $request->basic[$key];
            $payrolls->employee_id = $val;
            $payrolls->save();
        }
    }

    return redirect('/');
}
Sign up to request clarification or add additional context in comments.

1 Comment

Getting error in_array() expects at least 2 parameters, 1 given

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.