简体   繁体   中英

How can I insert multiple rows to the database in Laravel

I tried to save multiple rows to the database with one query, without success. I used a for loop but it can't retrieve the value of the inputs that are generated using jQuery after setting the number of rows.

Controller

public function store(Request $request)
{
    $nbrrowsol = $request->get('nbrrowsol');
    for ($i = 1; $i < $nbrrowsol; $i++) {
        $commande = new Commande();
        $commande->nom_client = $request->get('nomclient');
        $commande->organisme = $request->get('organisme');
        $commande->adresse = $request->get('adresse');
        $commande->email = $request->get('email');
        $commande->tel1 = $request->get('tel');
        $commande->tel2 = $request->get('tel2');
        $commande->fax = $request->get('fax');
        $commande->commercial = $request->get('commercial');
        $commande->date_reception = $request->get('datereception');
        $commande->date_prelevement = $request->get('dateprelev');
        $commande->saved_by = $request->get('savedby');
        $commande->code = $request->get('codesol' + $i);
        $commande->nature = $request->get('naturesol' + $i);
        $commande->reference_cli = $request->get('reference_clisol' + $i);
        $commande->profondeur = $request->get('profondeursol' + $i);
        $commande->culture = $request->get('culturesol' + $i);
        $commande->variete = $request->get('varietesol' + $i);
        $commande->gps = $request->get('gpssol' + $i);
        $commande->analyse_demande = $request->get('analysedemandesol' + $i);
        $commande->valide = $request->get('checkvalidee');
        $commande->save();
    }

    return redirect('gestion_commandes/create');
}

I get the following error after the user submits for saving data.

A non-numeric value encountered

I think that I didn't use (for) correctly or the form of:

$commande->code = $request->get('codesol' + $i);

错误图片

在此处输入图片说明

You seem to be fetching input using + addition operator which is for javascript, in PHP . operator is used for concatenation, also you'll need to fetch inputs it using the index of your inputs array, for example when your <input name="nomClient[]">

$request->get('nomclient['. $i . ']')

First of all to concat a string in PHP is done using . (dot) notation, not + . So this 'codesol'+$i should become 'codesol' . $i 'codesol' . $i and so on for the rest.

If you want to insert multiple rows directly, then take a look at this example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM