How to make an @foreach with Table Relationship in Laravel

0

I'm using the Laravel freamwork where in my database I have 2 tables:  - > claimants (with the field 'id', 'claimant', 'type_id')  - > types (with the fields 'id', 'name')

Both are already with the Complainant Model Relationship

public function tipoacao(){
    return $this->hasMany(TipoAcoes::class, 'id', 'tipoacao_id');
}

Controller:

public function edit($id){
    $titulo = "Edita Reclamante";
    $reclamantes = $this->reclamante->find($id);
    return view('admin.reclamante.create-edit', compact('titulo','reclamantes'));
}

But I'm not able to bring the data with field 'name' of the table 'types' within an imput select

     <div class="input-group col-xs-12">
          <select class="form-control" id="tipoacao_id" name="tipoacao_id" required value="{{$reclamantes->tipoacao->nome or old('$reclamantes->tipoacao->nome')}}">
               @foreach($reclamantes as $Rel)
                    <option value="{{$Rel->tipoacao->id}}">{{$Rel->tipoacao->nome}}</option>
               @endforeach
            </select>
    
asked by anonymous 27.09.2018 / 02:58

2 answers

2

In your controller, I think your query is being done in the wrong way. The $this makes a reference to the current class, in your case, the controller. Then% w /% would not result in anything. The correct would be:

public function edit($id){
    $titulo = "Edita Reclamante";
    $reclamantes = Reclamante::find($id);
    return view('admin.reclamante.create-edit', compact('titulo','reclamantes'));
}

Do not forget to declare the use of the Model Complainant.

After this query, within your $ claimants you will have the reference to the type, so just go through this option within your $this->reclamante variable and get the fields.

@foreach($reclamantes->tipoacao as $tipoacao)
    <option value="{{$tipoacao->id}}">{{$tipoacao->nome}}</option>
@endforeach

Remembering that I am assuming these are the attributes and names created in your Model.

    
27.09.2018 / 04:28
0

The problem is that you've listed wrong in your Model. You have changed the order of the parameters.

public function tipoacao(){
    return $this->hasMany( TipoAcoes::class, 'tipoacao_id', 'id'); // 1º parâmetro é a classe que vai relacionar, o 2º é a foreign_key e o 3º é a local_key
}

Take a look at the documentation to get any questions.

    
27.09.2018 / 16:36