problem when relating to the ORM eloquent de laravel


I am working on an application in laravel 5.5 that works with tabs (personal data) and I have the respective table I also have a table communes that is related to the tabs table is to say a one-to-one relationship a tab can have a commune, I have several chips and when I go to look for the relationship with the communes I get the error I will show you my code

the method of myController tab

public function BuscarFicha(){
      $fichas= fichas::all();
        return view('Ficha.BuscarFicha',compact('fichas'));

the chip model

 public function comuna()
        return $this->belongsTo(comunas::class);

if I do it like that


No problem but I want to bring all the chips, in which I can be wrong?

asked by Pablo Moraga 28.02.2018 в 20:59

2 answers


If what you want is to show all the chips obtained and their respective communes, the first thing you should do is load the relationship at the time of obtaining the chips, to avoid a problem of N + 1:

$fichas  = fichas::with('comuna')->get();

Subsequently, in blade, you can use @forelse to iterate through the collection and display its information:

@forelse ($fichas as $ficha)
     Nombre de ficha: {{ $ficha->nombre }}
     Nombre de comuna: {{ $ficha->comuna->nombre }}
  <p>No hay fichas</p>

I used the name as a hypothetical example, but you simply replace the respective properties.




answered by 28.02.2018 / 21:13

What you should do when declaring the relationship with your model Chips is

public function comuna()
    // Debe de recibir el nombre completo de la clase
    return $this->belongsTo(Comunas::className());

Eager loading what you do is avoid making a query every time you call $ficha->comuna , which would be the select of the commune table looking for the id_ficha .

answered by 28.02.2018 в 21:27