Home > Software design >  How can I insert data from get() in laravel?
How can I insert data from get() in laravel?

Time:09-30

I want to insert data from get() method in L_Examen_Categorie table but it says :

Cannot insert explicit value for identity column in table 'L_Examen_Categorie' when IDENTITY_INSERT is set to OFF. (SQL: insert into [L_Examen_Categorie] ([id], [code], [libelle], [coefficient], [Note], [id_examen]) values (5, 777, 777, 3, 12, 1))"

Here is it my code

 $categorie = DB::table('P_Examen_Categorie as p')
            ->where('p.id_examen', '=', $request->input('id_examen'))
            ->get();
        foreach($categorie as $cat_item)
        {
            L_Examen_Categorie::insert((array)$cat_item);;
        }

Categorie reponse:

[{id: "5", code: "777", libelle: "777", coefficient: "3", Note: "12", id_examen: "1"},…]
0: {id: "5", code: "777", libelle: "777", coefficient: "3", Note: "12", id_examen: "1"}
1: {id: "7", code: "39", libelle: "39", coefficient: "3", Note: "12", id_examen: "1"}
2: {id: "9", code: "777", libelle: "39", coefficient: "3", Note: "12", id_examen: "1"}
3: {id: "10", code: "777", libelle: "777", coefficient: "1", Note: "1211", id_examen: "1"}
4: {id: "11", code: "777", libelle: "777", coefficient: "3", Note: "12", id_examen: "1"}

CodePudding user response:

You need to use the "toArray()" method. This method converts your collection object into an array and then inserts data.

$categorie = DB::table('P_Examen_Categorie as p')
->where('p.id_examen', '=', $request->input('id_examen'))
->get()->toArray();

L_Examen_Categorie::insert( $categorie); 

But make sure the same column is available in the L_Examen_Categorie tables

CodePudding user response:

Convert objects to associative array before inserting.

$categorie = json_decode($categorie, true);

L_Examen_Categorie::insert($categorie);
  • Related