Oussama Ammy Driss
Oussama Ammy Driss

Reputation: 37

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);

Error image

Upvotes: 0

Views: 112

Answers (2)

Aditya Thakur
Aditya Thakur

Reputation: 2610

enter image description here

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 . ']')

Upvotes: 1

nakov
nakov

Reputation: 14268

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

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

Upvotes: 0

Related Questions