Laravel : Add fields in two tables (Related Tables)

Asked

Viewed 206 times

-2

I have a problem in Laravel where I have two related tables.

I have a form for Tabela1 (Chapter) and a form for table 2 (documentation)

I can add "Chapters" without interfering with the other table. But when I try to add data in the document form gives error and says that the table parameter chapter is empty.

I have the following controller :

public function insert(Request $request){
   
    $tabela = new capitulo();
    $tabela->capitulo = $request->capitulo;

    $itens = capitulo::where('capitulo', '=', $request->capitulo)->count(); 
    if($itens > 0){
        echo "<script language='javascript'> window.alert('Já existe um capitulo com esse nome!') </script>";
        return view('gestao-documental');
       //return redirect()->route('GestaoDocumental');
    }

    $tabela->save();
  


    return redirect()->route('documentacao.index');
}


public function insert2(Request $request){
   
           //--------------------------------------------------

           $doc = new documentacao();
           $doc->id_capitulo = $request->id_capitulo;
           $doc->nome_ficheiro = $request->nome_ficheiro;
   
           if ($request->file('ficheiro')->isValid()){
               $request->file('ficheiro')->store('ficheiro/documentacao');    
           }
           //$doc->ficheiro = $request->file(ficheiro);
           $doc->versao = $request->versao;
           $doc->data_ultima_alteracao = $request->versao; 
   
   
           //dd($request->file('ficheiro')->isValid());
   
   
           $doc = documentacao::where('nome_ficheiro', '=', $request->nome_ficheiro)->count(); 
           if($doc > 0){
               echo "<script language='javascript'> window.alert('Já existe um capitulo com esse nome!') </script>";
               return view('gestao-documental');
              //return redirect()->route('GestaoDocumental');
           }
   
   
           
           
           $doc->save();
    
    return redirect()->route('GestaoDocumental');
}

EDIT: At this time the error that occurs is SQLSTATE[23000]: Integrity Constraint Violation: 1048 Column 'chapter' cannot be null (SQL: Insert into capitulos (capitulo) values (?))

The table "main"".

When inserting into documents requires the title table to be filled in

MODEL chapter:

    class capitulo extends Model
     {
     public $timestamps = false;
     use HasFactory;

      public function documentos() {

     return $this->hasMany(documentacao::class,'id_capitulo');
     }
}

MODEL Documentacao:

class documentacao extends Model
{
  public $timestamps = false;
  use HasFactory;
}

VIEW:

  <form id="form-perfil" method="POST" action="{{route('documentacao.insert2')}}" enctype="multipart/form-data">
                @csrf

                                        <div class="modal-body">

                        
                                <div class="form-group">
                                    <label >Capitulo Associado</label>
                                    <select class="form-select" aria-label="Default select example">
                                        <option selected>Escolher Capitulo</option>
                                        @foreach($capitulos as $cap)
                                        <option class="form-control" id="id_capitulo" name="id_capitulo"> {{$cap->capitulo}}</option>
                                        @endforeach 
                                        </select>
                                        <input value="" type="text" class="form-control" id="id_capitulo" name="id_capitulo" placeholder="Capitulo">
                                    </div>

                                <div class="form-group">
                                    <label >Nome Ficheiro</label>
                                    <input value="" type="text" class="form-control" id="nome_ficheiro" name="nome_ficheiro" placeholder="Nome Ficheiro">
                                </div>

                                
                                <div class="form-group">
                                    <label >Adicionar Ficheiro</label>
                                    <input type="file" class="form-control" name="ficheiro" id="ficheiro" />
                                </div>

                                <div class="form-group">
                                <label >Versão</label>
                                <input value="" min="1"  value="1" step="0.1" type="number" class="form-control" id="versao" name="versao" placeholder="Versão">
                                </div>

                                <div class="form-group">
                                    <label >Data alteração</label>
                                    <input type="date" class="form-control" id="data_ultima_alteracao" name="data_ultima_alteracao">
                                </div>

                    </div>
                    <div class="modal-footer">

                        <button type="button" id="btn-fechar" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                        <button type="submit" name="btn-salvar-perfil" id="btn-salvar-perfil" class="btn btn-primary">Guardar</button>
                    </div>
                </form>
  • Could you explain why here $doc = documentacao::where('nome_ficheiro', '=', $request->nome_ficheiro)->count(); you overwrite $doc by a numerical value and which has not yet saved the modifications?

1 answer

1


Change the test if a doc already exists to before starting the logic of creating a new case does not exist

public function insert2(Request $request){
   
     $doc = documentacao::where('nome_ficheiro', '=', $request->nome_ficheiro)->count(); 
     if($doc > 0){
         echo "<script language='javascript'> window.alert('Já existe um capitulo com esse nome!') </script>";
         return view('gestao-documental');
        //return redirect()->route('GestaoDocumental');
     }


    //--------------------------------------------------

    $doc = new documentacao();
    $doc->id_capitulo = $request->id_capitulo;
    $doc->nome_ficheiro = $request->nome_ficheiro;
   
    if ($request->file('ficheiro')->isValid()){
        $request->file('ficheiro')->store('ficheiro/documentacao');    
    }
    //$doc->ficheiro = $request->file(ficheiro);
    $doc->versao = $request->versao;
    $doc->data_ultima_alteracao = $request->versao; 
   
   
    //dd($request->file('ficheiro')->isValid());
   
          
           
    $doc->save();
    
    return redirect()->route('GestaoDocumental');
}

EDIT to resolve the view

Below I show you how to fix the View problem, which is not "identifying" the chapter. This is why you are not stating in the select option what the value of that selection is


<div class="form-group">
   <label>Capitulo Associado</label>
   <select class="form-select" aria-label="Default select example" name="id_capitulo">
      <option selected>Escolher Capitulo</option>
      @foreach($capitulos as $cap)
         <option class="form-control" value="{{$cap->id}}"> {{$cap->capitulo}}</option>
      @endforeach 
   </select>
</div>

  • Integrity Constraint Violation: 1048 Column 'capitulo' cannot be null (SQL: Insert into capitulos (capitulo) values (?)) have this error

  • Is it not the case that the chapter and the documentation in the sequence are included in the same controller method? See, it’s hard to give a better help if you don’t report details like a bank modeling or a screenshot of the screen

  • I’m going to put my models as they currently are. Inside my controller I’m trying to store them in two different tables that are related. When I run insert2, always ask me for the field of the other table

  • But in this code here in question you have no Chapter->save() for example to give error "Insert into chapters" .... I can’t see the error

  • I would say you are giving this error because the tables are related. Because the code should not give this error. A chapter may have N documents

  • select Count(*) as Aggregate from capitulos Where capitulo is null have this debug error

  • The point is that the err of Insert cannot be null in an Insert into chapters, that is to say q vc is trying to insert into the table chapters a null value in the chapter field, which cannot be null, but in the function insert2 vc does not have, at least not here in the question, an Insert to the table chapters, so I’m having trouble helping you ... I would need to see the code of the Blade, route q is calling and database schema, which is different from php code of the template

  • I have 2 problems.. In View (which I just put here) when I do @foreach the name Id_chapter does not pass to the controller. And when I try to save in the table does not need to make any reference to the table "main"

  • I edited the answer with the correction in Blade, working, I thank you mark the answer as correct and give an up on it

Show 4 more comments

Browser other questions tagged

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