Ahsan
Ahsan

Reputation: 1359

Laravel Store Value if Checkbox is Checked

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('/');
    }

Upvotes: 5

Views: 2380

Answers (1)

EchoAro
EchoAro

Reputation: 838

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('/');
}

Upvotes: 2

Related Questions