nionta's avatar

data is not saving in database

this is my controller file :

public function postdata(Request $request)
    {
    $month_year_multi_ids = $request->get('checkbox_Names');
    $company = $request->get('company');


    foreach ($month_year_multi_ids as $key => $value) {
        $last_space = strrpos($value, ' ');
        $year[] = substr($value, $last_space);
        $month[] = substr($value, 0, $last_space);
    }

    $validation = $request->validate([

        'company' => 'required',
        'checkbox_Names' => 'required',

    ]);

    $error_array = array();
    $success_output = '';


    if ($request->get('button_action') == "insert")
    {
        foreach ($month_year_multi_ids as $index => $values) {
            $company_year = new CompanyYear([

                'company_id'  => $company,
                'year' => $year[$index],
                'month' => $month[$index],

            ]);
            $company_year->save();
        }

    }
    $success_output = '<div class="alert alert-success">Data Inserted</div>';

    $output = array(
        'errror' => $error_array,
        'success' => $success_output
    );
    echo json_encode($output);

}

data is showing success , but data is not saving in database. also $company, $year and $month variable is showing the right value. where is the problem? why the data is not saving?

0 likes
5 replies
bobbybouwmann's avatar

Are you sure $month_year_multi_ids = $request->get('checkbox_Names'); this statement is giving you the correct data? It should give you an array with values from the selected items.

Let's do this step by step. What does the request give you back? You can test that by doing something like this

public function postdata(Request $request) 
{ 
    dd($request->all()):

    // Your other code
}
nionta's avatar

@bobbybouwmann , yes $month_year_multi_ids = $request->get('checkbox_Names'); return the right values, and dd($request->all()) also return the right result

newbie360's avatar
    if ($request->get('button_action') == "insert")
    {
        dd('ok');
        
        foreach ($month_year_multi_ids as $index => $values)
        {
            $company_year = new CompanyYear;
            $company_year->company_id = $company;
            $company_year->year = $year[$index];
            $company_year->month = $month[$index];
            $company_year->save();
        }

    }            

did you see ok ?

and why you loop two times of $month_year_multi_ids

combine the first and second loop, so no need use array $year[] $month[]

1 like
LearnHunter's avatar
just use laravel eloquent 
$data= $request->all();
then save it. why you write many lines.

nionta's avatar

@newbie360 I have found the solution , I was not passing button_action into the controller function.. now it's working fine, thank you

Please or to participate in this conversation.