Insert several records at once with ApiRestful - Laravel

0

I have the following question and I would like you to help me with this, you will see, I have in my controller to upload telephone equipment to my ApiRestful and everything done to be able to upload a computer by providing a "json", here the code:

public function store(Request $request)
    {
        $hash = $request->header('Authorization', null);

        $jwtAuth = new JwtAuth();
        $checkToken = $jwtAuth->checkToken($hash);

        if($checkToken)
        {
            //Conseguir el usuario identificado

            $user = $jwtAuth->checkToken($hash, true);

            //Guardar el auto

            $role = $user->role;
            if($role == 'SUPERUSUARIO')
            {
                //Recoger datos del post

                $json = $request->input('json', null);
                $params = json_decode($json, true);
                var_dump($params);

                $i = 0;
                $paramnew = [];
                foreach ($params as $param => $param_data) 
                {
                    $name_t[$i] = (!is_null($json) && isset($param_data['name_t'])) ? $param_data['name_t'] : null;
                    print_r($name_t);
                    $i++;
                }


                $name_t = (!is_null($json) && isset($params->name_t)) ? $params->name_t : null;
                $name_s = (!is_null($json) && isset($params->name_s)) ? $params->name_s : null;
                $marca = (!is_null($json) && isset($params->marca)) ? $params->marca : null;
                $marca_2 = (!is_null($json) && isset($params->marca_2)) ? $params->marca_2 : null;
                $modelo = (!is_null($json) && isset($params->modelo)) ? $params->modelo : null;
                $codigo_m = (!is_null($json) && isset($params->codigo_m)) ? $params->codigo_m : null;
                $busqueda = (!is_null($json) && isset($params->busqueda)) ? $params->busqueda : null;
                $color = (!is_null($json) && isset($params->color)) ? $params->color : null;
                $internet = (!is_null($json) && isset($params->internet)) ? $params->internet : null;
                $huella = (!is_null($json) && isset($params->huella)) ? $params->huella : null;
                $largo = (!is_null($json) && isset($params->largo)) ? $params->largo : null;
                $ancho = (!is_null($json) && isset($params->ancho)) ? $params->ancho : null;
                $grosor = (!is_null($json) && isset($params->grosor)) ? $params->grosor : null;
                $peso = (!is_null($json) && isset($params->peso)) ? $params->peso : null;
                $pantalla = (!is_null($json) && isset($params->pantalla)) ? $params->pantalla : null;
                $sistema = (!is_null($json) && isset($params->sistema)) ? $params->sistema : null;
                $version = (!is_null($json) && isset($params->version)) ? $params->version : null;
                $nucleos = (!is_null($json) && isset($params->nucleos)) ? $params->nucleos : null;
                $velocidad = (!is_null($json) && isset($params->velocidad)) ? $params->velocidad : null;
                $memoria = (!is_null($json) && isset($params->memoria)) ? $params->memoria : null;
                $sd = (!is_null($json) && isset($params->sd)) ? $params->sd : null;
                $ram = (!is_null($json) && isset($params->ram)) ? $params->ram : null;
                $cam_1 = (!is_null($json) && isset($params->cam_1)) ? $params->cam_1 : null;
                $flash_1 = (!is_null($json) && isset($params->flash_1)) ? $params->flash_1 : null;
                $cam_2 = (!is_null($json) && isset($params->cam_2)) ? $params->cam_2 : null;
                $flash_2 = (!is_null($json) && isset($params->flash_2)) ? $params->flash_2 : null;
                $bateria = (!is_null($json) && isset($params->bateria)) ? $params->bateria : null;
                $bandas_2g = (!is_null($json) && isset($params->bandas_2g)) ? $params->bandas_2g : null;
                $bandas_3g = (!is_null($json) && isset($params->bandas_3g)) ? $params->bandas_3g : null;
                $bandas_4g = (!is_null($json) && isset($params->bandas_4g)) ? $params->bandas_4g : null;

                if(!is_null($name_t))
                {
                    //Rellenar Variables

                    $telefono = new Telefono();
                    if(Telefono::all()->count())
                    {
                        $telefono_id = Telefono::orderBy('id', 'desc')->first()->id;
                    }
                    else
                    {
                        $telefono_id = 0;
                    }
                    $telefono->id = $telefono_id + 1;
                    $telefono->user_id = $user->sub;
                    $telefono->name_t = $name_t;
                    $telefono->name_s = $name_s;
                    $telefono->marca = $marca;
                    $telefono->marca_2 = $marca_2;
                    $telefono->modelo = $modelo;
                    $telefono->codigo_m = $codigo_m;
                    $telefono->busqueda = $busqueda;
                    $telefono->color = $color;
                    $telefono->internet = $internet;
                    $telefono->huella = $huella;
                    $telefono->largo = $largo;
                    $telefono->ancho = $ancho;
                    $telefono->grosor = $grosor;
                    $telefono->peso = $peso;
                    $telefono->pantalla = $pantalla;
                    $telefono->sistema = $sistema;
                    $telefono->version = $version;
                    $telefono->nucleos = $nucleos;
                    $telefono->velocidad = $velocidad;
                    $telefono->memoria = $memoria;
                    $telefono->sd = $sd;
                    $telefono->ram = $ram;
                    $telefono->cam_1 = $cam_1;
                    $telefono->flash_1 = $flash_1;
                    $telefono->cam_2 = $cam_2;
                    $telefono->flash_2 = $flash_2;
                    $telefono->bateria = $bateria;
                    $telefono->bandas_2g = $bandas_2g;
                    $telefono->bandas_3g = $bandas_3g;
                    $telefono->bandas_4g = $bandas_4g;

                    //Comprobar telefono duplicado
                    $isset_telefono = Telefono::where('name_t', '=', $name_t)->first();

                    if(count($isset_telefono) == 0)
                    {
                        //Guardar el registro
                        $telefono->save();

                        $data = [
                                'telefono' => $name_t,
                                'status' => 'success',
                                'code' => 200,
                                'message' => 'Telefono creado satisfactoriamente'
                                ];
                    }
                    else
                    {
                        $data = [
                            'status' => 'error',
                            'code' => 400,
                            'message' => 'El telefono "'.$name_t.'" ya existe.'
                            ];
                    }
                }
                else
                {
                    $data = [
                            'status' => 'error',
                            'code' => 400,
                            'message' => 'Telefono no creado, el nombre comercial es requerido'
                            ];
                }

            }
            else
            {
                //Devolver error

                $data = [
                    'message' => 'Role insuficiente para hacer esta acción.',
                    'status' => 'error',
                    'code' => 300
                    ];
            }
        }
        else
        {
            //Devolver error

            $data = [
                    'message' => 'Hay que estar logeado para hacer esta acción',
                    'status' => 'error',
                    'code' => 300
                    ];
        }

        return response()->json($data, 200);
    }

My problem is that for me to upload teams I will not upload them "1 x 1" but of an excel with all the equipment that a telephone company passes me I do the conversion and I return everything in a "json" similar to the following: then with that "json" already created I would like my phone controller to upload each of the equipment that is there, I have thought about possibilities, maybe a foreach that repeats each of the "name_t" that would be my foreign key in the database and therefore the only value needed to upload a computer, because all other values are optional, with only being able to upload that value to the database by passing a "json" where there are many "name_t" and I take them as different registers, life would be very difficult for me and I would manage to make the same thing happen with the other data.

PS: if you ask why in "$ telefono-> id" I put an id in that way, it's because the database is not an "auto_increment" field, since it's not my only key and I could not put it as the only key since the my phones the "name_t" is linked to another table of "prices"

    
asked by Enrique Marrero 15.05.2018 в 09:04
source

2 answers

0

My solution was the following one, for whom it interests you can take reference, in this way I raised the "json" of many telephones, doing a foreach of the information and one goes "1 x 1"

public function store(Request $request)
    {
        $hash = $request->header('Authorization', null);

        $jwtAuth = new JwtAuth();
        $checkToken = $jwtAuth->checkToken($hash);

        if($checkToken)
        {
            //Conseguir el usuario identificado

            $user = $jwtAuth->checkToken($hash, true);

            //Guardar el telefono

            $role = $user->role;
            if($role == 'SUPERUSUARIO')
            {
                //Recoger los datos por POST

                $json = $request->input('json', null);
                $params = json_decode($json);
                $params_array = json_decode($json, true);

                $i = 0;
                foreach ($params_array AS $param => $paramdata) 
                {
                    //Verificar el id del ultimo telefono existente   
                    if(Telefono::all()->count())
                    {
                        $telefono_id = Telefono::orderBy('id', 'desc')->first()->id + 1;
                    }
                    else
                    {
                        $telefono_id = 1;
                    }

                    //Crear objeto $telefono
                    $telefono = new Telefono();

                    //Rellenar Variables
                    $telefono->id = $telefono_id;
                    $telefono->user_id = $user->sub;
                    $telefono->name_t = $paramdata['name_t'];
                    $telefono->name_s = $paramdata['name_s'];
                    $telefono->marca = $paramdata['marca'];
                    $telefono->marca_2 = $paramdata['marca_2'];
                    $telefono->modelo = $paramdata['modelo'];
                    $telefono->codigo_m = $paramdata['codigo_m'];
                    $telefono->busqueda = $paramdata['busqueda'];
                    $telefono->color = $paramdata['color'];
                    $telefono->internet = $paramdata['internet'];
                    $telefono->huella = $paramdata['huella'];
                    $telefono->largo = $paramdata['largo'];
                    $telefono->ancho = $paramdata['ancho'];
                    $telefono->grosor = $paramdata['grosor'];
                    $telefono->peso = $paramdata['peso'];
                    $telefono->pantalla = $paramdata['pantalla'];
                    $telefono->sistema = $paramdata['sistema'];
                    $telefono->version = $paramdata['version'];
                    $telefono->nucleos = $paramdata['nucleos'];
                    $telefono->velocidad = $paramdata['velocidad'];
                    $telefono->memoria = $paramdata['memoria'];
                    $telefono->sd = $paramdata['sd'];
                    $telefono->ram = $paramdata['ram'];
                    $telefono->cam_1 = $paramdata['cam_1'];
                    $telefono->flash_1 = $paramdata['flash_1'];
                    $telefono->cam_2 = $paramdata['cam_2'];
                    $telefono->flash_2 = $paramdata['flash_2'];
                    $telefono->bateria = $paramdata['bateria'];
                    $telefono->bandas_2g = $paramdata['bandas_2g'];
                    $telefono->bandas_3g = $paramdata['bandas_3g'];
                    $telefono->bandas_4g = $paramdata['bandas_4g'];

                    //Comprobar telefono duplicado
                    $isset_telefono = Telefono::where('name_t', '=', $paramdata['name_t'])->first();
                    $update_telefono = Telefono::where('name_t', '=', $paramdata['name_t']);

                    if(count($isset_telefono) == 0)
                    {
                        //Guardar el registro

                        $telefono->save();

                        //Devolverlo
                        $data = [
                                'status' => 'success',
                                'code' => 200,
                                'message' => 'Telefonos creados satisfactoriamente, ultimo telefono en ser subido: '.$paramdata['name_t']
                                ];
                    }
                    else
                    {
                        $update_telefono->update($paramdata);

                        $data = [
                                'telefono' => $paramdata['name_t'],
                                'status' => 'success',
                                'message' => 'Telefono actualizado satisfactoriamente',
                                'code' => 200
                                ];  
                    }
                }
            }
            else
            {
                //Devolver error

                $data = [
                    'message' => 'Role insuficiente para hacer esta acción.',
                    'status' => 'error',
                    'code' => 300
                    ];
            }
        }
        else
        {
            //Devolver error

            $data = [
                    'message' => 'Hay que estar logeado para hacer esta acción',
                    'status' => 'error',
                    'code' => 300
                    ];
        }

        return response()->json($data, 200);
    }
    
answered by 16.05.2018 в 23:02
0

The code of your solution seems to me that you can optimize a lot.

From the start it is not clear to me how are you receiving the $request->json but I think that you could calmly do

foreach ($request->json AS $param => $paramdata) {  }

Afterwards I do not understand what you are doing to get the id
If you define it in the migration as increments this field is autocomplete without needing you to specify it.

It also seems that the fields of your json are equal to those of the table so you could directly do Telefono::create($paramdata); (Make sure they are as fillable in your Phone Model)

Finally, if there can not be a duplicate name in the migration, place it in your field name_t ->unique();

THE FIELD ID SHOULD BE AUTOINCREMENT $table->increments('id');
THE FIELD name_t SHOULD BE SINGLE $table->string('name_t')->unique();

public function store(Request $request) 
{
    $hash = $request->header('Authorization', null);

    $jwtAuth = new JwtAuth();
    $checkToken = $jwtAuth->checkToken($hash);

    if($checkToken)
    {
        // Conseguir el usuario identificado
        $user = $jwtAuth->checkToken($hash, true);

        // Conseguir el rol del usuario identificado
        $role = $user->role;
        if($role == 'SUPERUSUARIO')
        {
            // Recoger los datos por POST
            $params_array = $request->json; 
            // En la captura de pantalla pareciera ser 
            // que estás recibiendo todo en la llave **precios** 
            // así que quiza es $request->precios

            $data = collect(); // Creo que no es necesario

            foreach ($params_array as $param => $paramdata) 
            {
                // Crear Telefono Nuevo o Actualizar existente
                $telefono = Telefono::updateOrCreate(
                                      ['name_t' => $paramdata['name_t']], 
                                      $paramdata
                                    );
                $data->push($telefono); // Creo que no es necesario
            }
        }
        else
        {
            //Devolver error
            $data = [
            'message' => 'Role insuficiente para hacer esta acción.',
            'status' => 'error',
            'code' => 300
            ];
        }
    }
    else
    {
        //Devolver error

        $data = [
                'message' => 'Hay que estar logeado para hacer esta acción',
                'status' => 'error',
                'code' => 300
                ];
    }

    return response()->json($data, 200); // Creo que no es necesario
    // Yo haría return response()->json(['message' => 'Success'], 200);
}

I do not consider the records loaded or updated as an important fact, since you could ask for a telephone number, so I would omit that part of collecting the telephones.

I do not want to get into the issue of authentication so I left it the same, but you could use a middleware in the path to verify if the user is authenticated and another middleware to verify the role it has and in that case the method it would be:

public function store(Request $request) 
{
    foreach ($request->json as $param => $paramdata) 
    {
        $telefono = Telefono::updateOrCreate(
                              ['name_t' => $paramdata['name_t']], 
                              $paramdata
                            );
    }

    return response()->json(['message' => 'Success'], 200);
}
    
answered by 18.05.2018 в 04:47