How to fix error: String data, right truncated: 1406

Asked

Viewed 3,366 times

-2

Hello, follow my question:


I am trying to save the Protocol Checklist data, but the following error is occurring:

SQLSTATE[22001]: String data, right truncated: 1406 Data Too long for column 'item' at Row 1

How to solve this problem?

1. Follows the image of the modal Checklist Protocol: It is the form responsible for receiving the data entered by the user. inserir a descrição da imagem aqui

2. Follows the error image when trying to enter the data: inserir a descrição da imagem aqui 3. Registration methodChecklistProtocolo of the Projectocontroller.php class This method is responsible for registering the Checklist protocol data in the database.

   public function cadastroChecklistProtocolo(Request $request)

    {
        // Deletar a tabela de checklist_protocolo
       $checklistsProtocolos = ChecklistProtocolo::where('projeto_id', $request->projeto_id)->delete();

 $data = $request->all();
        $dataInsert = [];
            //Observe que eu tirei o push ($dataInsert[]) pois assim iria adicionar mais uma array no fim 
            $dataInsert = [
                'projeto_id' => $data['projeto_id'],
                'item' => $data ['item'],
                'modelo_id' => $data['modelo_id'],
                'item_descricao_id' => $data ['item_descricao_id'],
                'sim_nao' => $data ['sim_nao'],
                'nao_atende' => $data ['nao_atende'],
                'dt_validade' => $data ['dt_validade'],
                'pagina_documento' => $data ['pagina_documento'],
                'observacao' => $data ['observacao'],

            ];

            //dd($dataInsert);
           $dados =  ChecklistProtocolo::create($dataInsert); 

     $response= true;

        if($response)
        {
            return redirect()
                      ->route('projeto.edita', $request->projeto_id) 
                      ->with('success',"Sucesso ao atualizar os Checklists do Protocolo");
        }else
        {
            return redirect()
                      ->back()
                      ->with('error',"Erro ao atualizar o Checklists do Protocolo"); 
        } 
    }     

4. Modal Checklistprotocol Code:

  <!--Inicio do modal de Checklist do Projeto-->
<form id="checklistProtocolo" action="{{route('projeto.cadastroChecklistProtocolo')}}" method="POST">

                  {{ csrf_field() }}  
  <div class="modal fade modal-default" id="modalChecklist" aria-hidden="true" aria-labelledby="examplePositionCenter"
                 role="dialog" tabindex="-1">

                <div class="modal-dialog2 modal-center">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">×</span>
                            </button>
                            <h4 class="modal-title">Checklists do Protocolo</h4>
                        </div>

                        <div class="form-group col-md-4">
                             <input type="hidden" id="projeto_id" name="projeto_id" value="{{$projeto->id}}">
                             <input type="hidden" id="modelo_id"  name="modelo_id" value="{{$modeloProtocolo[0]['id']}}">
                             <label class="control-label">Modelo</label>
                             <input type="text" class="form-control" name="modeloProcesso" value="{{$modeloProtocolo[0]['modelo']}}" disabled> 

                        </div>
                        <div class="modal-body">
                        <div class="form-group col-md-18">

                             <table id="checklistProtocolo" name="checklistProtocolo" class="table table-hover table-striped table-responsive toggle-arrow-tiny" >
                                <caption></caption>
                                    <thead>
                                        <tr>
                                            <th>Item</th> 
                                            <th>Descrição</th>
                                            <th>Sim/Não</th>
                                            <th>Não Atende</th>
                                            <th>Data de Validade</th>
                                            <th>Página do Documento</th>
                                            <th><center>Observações</center> </th>
                                            <th class="text-center"></th>
                                        </tr>
                                    </thead>
                                    <tbody id="bodyChecklists">

                            @foreach($checklistsProtocolos as $checklistProtocolo)

                                <tr>
                                    <td><input type="text" class="form-control"  id="item" name="item[]" value="{{$checklistProtocolo->item}}"  size ="2"></td>
                                    <td>{{$checklistProtocolo->descricao_item}}</td>   
                                    <input type="hidden"          id="item_descricao_id"  name="item_descricao_id[]" value="{{$checklistProtocolo->item_descricao_id}}">
                                    <td><input type="checkbox"    id="sim_nao"            name="sim_nao[]"    {{$checklistProtocolo->sim_nao == null ? '' : 'checked'}}></td>
                                    <td><input type="checkbox"    id="nao_atende"         name="nao_atende[]" {{$checklistProtocolo->nao_atende == null ? '' : 'checked'}}></td>
                                    <td><input type="date"        id="dt_validade"        name="dt_validade[]" value="{{$checklistProtocolo->dt_validade}}"></td>
                                    <td><input type="text"        id="pagina_documento"   name="pagina_documento[]" value="{{$checklistProtocolo->pagina_documento}}" size ="1"></td>
                                    <td><input type="text"        id="observacao"         name="observacao[]" value="{{$checklistProtocolo->observacao}}" size ="1" style="width: 300px; height: 60px"></td>
                                </tr>

                            @endforeach 

                               </tbody>
                        </table>



                        </div>

                        </div><!--Fim do modal-body-->

                        <div class="modal-footer">
                        <center>
                        <button type="submit" class="btn btn-primary"  aria-hidden="true" style="width: 300px; height: 40px" > Salvar</button>

                        </center>
                        </div>
                    </div>
                </div>
            </div>
            </form>  
  <!--Fim do modal do Checklist do Projeto-->    

5. Checklistprotocol.php template code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;
use SoftDeletes;

class ChecklistProtocolo extends Model
{
    protected $table = "checklist_protocolo";

    protected $primaryKey =  ['projeto_id', 'modelo_id','itens_descricao_id'];

    public $incrementing = false;

    public $timestamps = false;

    protected  $fillable  = ['projeto_id', 'modelo_id','item','itens_descricao_id','sim_nao', 'nao_atende','dt_validade','pagina_documento','observacao'];

    protected $casts = [ 'item' => 'array', 'item_descricao_id'=> 'array','sim_nao' => 'array', 'dt_validade'=> 'array', 
    'pagina_documento'=> 'array', 'observacao'=> 'array', 'nao_atende'=> 'array'];

    /* 
    public function checklistProtocolo()
    {
         return $this->belongsTo(ChecklistProtocolo::class, 'projeto_id','modelo_id', 'itens_descricao_id');
    } */

    //Este método salva os dados do Checklist do Protocolo
    public function salvar(ChecklistProtocolo $checklistProtocolo) : Array
    {
       $checklistProtocolo = $this->save();

         if($checklistProtocolo){

            return[
                'success' => true,
                'message' => 'Sucesso ao cadastrar'
            ];   
        }
        else{

            return[
                'success' => false,
                'message' => 'Falha ao cadastrar'
            ]; 
        }
    }


    //Este método remove os dados do Checklist do Protocolo
  public function deletar(checklistProtocolo $checklistProtocolo) : Array
  {
      $checklistProtocolo =  $this->delete();
      if($checklistProtocolo){

          return[
              'success' => true,
              'message' => 'Sucesso ao excluir'
          ];   
      }
      else{

          return[
              'success' => false,
              'message' => 'Falha ao excluir'
          ]; 
      }
  }


//Este método atualiza os dados do  Checklist do Protocolo
public function alterar(checklistProtocolo $checklistProtocolo) : Array
{
  $checklistProtocolo = $this->save();
    if($checklistProtocolo){
        return[
            'success' => true,
            'message' => 'Sucesso ao atualizar'
        ];   
    }
    else{
        return[
            'success' => false,
            'message' => 'Falha ao atualizar'
        ]; 
    }
}


}

6. Debugging of the variable "$request->all();"
inserir a descrição da imagem aqui

7. Model ER"
inserir a descrição da imagem aqui

8. Description of the database table inserir a descrição da imagem aqui

  • Your modelo_id is directly within the $request->all() but you try to access it within the loop

  • The right thing would be 'projeto_id' => $data['projeto_id'] and the loop should be done only in fields where there is array: Item, item_descricao_id, sim_nao etc...

  • Thank you for the @edsonalves reply. I tested the way you said, but the following error occurred: Illegal string offset 'item'.

  • Is that the item is also at level 0 of the array... With "loop in which are arrays" I meant something like: foreach ($data['item'] as $items) { and go through its values... But you don’t need to make a direct loop on $data just pick up the values directly

  • Segue o método: public function cadastroChecklistProtocolo(Request $request){&#xA;$data = $request->all();$dataInsert = []; $dataInsert['projeto_id'] = $data['projeto_id']; $dataInsert['modelo_id'] = $data['modelo_id'];

  • foreach ($date as $dataForm) {$dataInsert[] = ['item' => $dataForm['item'], 'item_descricao_id' => $dataForm['item_descricao_id'],'sim_nao' => $dataForm['sim_nao'], 'dt_validade' => $dataForm['dt_validade'], 'pagina_documento' => $dataForm['pagina_documento'], 'observacao' => $dataForm['observacao'], 'nao_atende' => $dataForm['nao_atende'],];

  • $data = Checklistprotocol::create($dataInsert);$data->save(); }}

  • Update your question with this data, it is not cool to put such large snippets in the comments

  • Hello @Edson Alves. The question has been updated. I would like you to show me an example.

Show 4 more comments

2 answers

1

According to my comment, it is not necessary to loop the data $data just access directly:

Note: If I am not prepared to accept arrays this line $dados = ChecklistProtocolo::create($dataInsert); will result in error, since dataInsert is a 2 level array.

       $data = $request->all();
        $dataInsert = [];
            //Observe que eu tirei o push ($dataInsert[]) pois assim iria adicionar mais uma array no fim 
            $dataInsert = [
                'projeto_id' => $data['projeto_id'],
                'modelo_id' => $data['modelo_id'],
                'item' => $data ['item'],
                'item_descricao_id' => $data ['item_descricao_id'],
                'sim_nao' => $data ['sim_nao'],
                'dt_validade' => $data ['dt_validade'],
                'pagina_documento' => $data ['pagina_documento'],
                'observacao' => $data ['observacao'],
                'nao_atende' => $data ['nao_atende'],
            ];
           $dados =  ChecklistProtocolo::create($dataInsert);
           $dados->save();

Update

The mistake

SQLSTATE[22001]: String data, right truncated: 1406 Data Too long for column 'item' at Row 1 It happens because your item column (and others) does not have enough space to save the data, being only 10 characters.

When using the cast, your array will be converted into string to be saved, which generates a string much larger than 10 characters.

  • Hello, @Edson. I tested your solution, but the following error occurred: Array to string Conversion (SQL: Insert into checklist_protocolo (projeto_id, item, modelo_id, sim_nao, nao_atende, dt_validade, pagina_documento, observacao) values (12, 0, 7, on, on, 2018-11-28, 1, Tetes))

  • As I said, "If I’m not prepared to accept arrays this line $data = Checklistprotocol::create($dataInsert); will result in error, since dataInsert is a 2-level array." , you are trying to insert an array in the database, you can add a mutator in your model for each value with array, example protected $casts = [&#xA; 'item' => 'array',&#xA; ];

  • Would be: $casts = [ 'item' => 'array', 'item_descricao_id'=> 'array' [...]]; doing this for each of the values that are array... There are other ways to do, for example separating into tables, but so I think it will be easier

  • https://laravel.com/docs/5.7/eloquent-mutators#attribute-casting

  • Hi @Edson Alves. I entered the $cast variable in the template. But when saving the data the following error occurred: SQLSTATE[22001]: String data, right truncated: 1406 Data Too long for column 'item' at Row 1.

  • The question has been updated.

  • It seems that your column does not have enough space to accept the string. What is its type and size? Add your Migration to the question.

  • The description of the table was inserted in the doubt.

Show 3 more comments

1

Solution for the project in question was to create a variable ($cont) to count row of each array within the loop that will be reflected in the View.

Reference: Save items from a Checklist form in the database - Laravel

Follows code:

for($i = 0; $i < count($dt_validade); $i++){

                   $dataInsert = array(
                         'sim_nao' => $sim_nao[$cont],                   
                         'dt_validade'=> $dt_validade[$cont], 
                         'pagina_documento' =>$pagina_documento[$cont], 
                         'observacao' =>$observacao[$cont]);           

                         $checklistsProtocolos = checklistProtocolo::where('projeto_id', $projeto_id)
                         ->whereIn('item_descricao_id', (array)$item_descricao_id[$cont])  //atualiza linha por linha do array
                         ->update($dataInsert);
                         $cont++; //atualiza linha por linha do array
                  } 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.