Ad

How To Get An Element In Each Row From A Complete Array In Laravel?

- 1 answer

I'm inserting a group of elements in database, I'm trying to get one element for each row but I'm obtaining all elements in one row and every row from the database is repeated like this

enter image description here

I would like to get one element for row in the column.. I'm using this query

$data = DB::table('incidencias')
   ->join('clientes_incid', 'clientes_incid.rif', '=', 'incidencias.rif')
   ->select('incidencias.rif')
   ->distinct()
   ->get();

    foreach ($data as $val) { 
    DB::table('clientes_view')->insert(['resultado' => $data]);

How could I fix it?

Ad

Answer

Because you are inserting the $data instead of $val,

You can get all $data, and insert them at once, like this:

$data = DB::table('incidencias')
   ->join('clientes_incid', 'clientes_incid.rif', '=', 'incidencias.rif')
   ->select('incidencias.rif AS resultado')
   ->distinct()
   ->get();
// If you are using Eloquent, you can just use ->toarray();
// For query builder, you need to change stdClass to array, so I use json_decode()
$data = json_decode(json_encode($data, true), true);

DB::table('clientes_view')->insert($data);

updateOrInsert only supports one record, so if you want to use this method:

$data = DB::table('incidencias')
   ->join('clientes_incid', 'clientes_incid.rif', '=', 'incidencias.rif')
   ->select('incidencias.rif AS resultado')
   ->distinct()
   ->get();
$data = json_decode(json_encode($data, true), true);
forEach($data as $val) {
    DB::table('clientes_view')->updateOrInsert($val, $val);
}
Ad
source: stackoverflow.com
Ad