How to make a @foreach with Relationship Tables in Laravel

Asked

Viewed 399 times

0

I’m using Laravel freamwork where in my database I have 2 tables: -> complainants (with the field 'id','complainant','typoacoes_id') -> typos (with id fields, 'name')

Both are already with the Relationship in Model Complainant

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 am not able to bring the data with field 'name' of table 'typoacoes' 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>
  • I think you can formulate a better question. Maybe with sample codes (maybe what you’re using), or a clearer question. The way it is, it’s hard to help you

  • Thanks friend! I’m new around here this is my first question rs... I think with your advice gave p/ detail more!

2 answers

2

In your controller I believe that your query is being made in the wrong way. The $this refers to the current class, in your case, the controller. Then the $this->reclamante would result in nothing. The right thing would be:

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

Don’t forget to declare the use of the Complaining Model.

After this query, within your $complainants will have the reference to the type, so just scroll through this option within your variable $reclamantes and get the fields.

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

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

  • My Controller is so because it has a Construct above public Function __Construct(Complainant $complainant){ $this->complainant = $complainant; } But anyway, it worked, I put @foreach as you did and it worked Thanks!

0

The problem is that you related wrong in your Model. You 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 documentation to remove any doubt.

Browser other questions tagged

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