3

I have this given table structure:

enter image description here

How can I access the 'curso.name' from my 'visita' class using eloquent? I assigned the many to many relationships but can only access the 'turma.curso_id', but I wanna get something like $visita->curso['nome'].

I wanna know how to avoid needing Curso::all().

Added some snippets below:

// Class VISITA    
class Visita extends Model
{

      protected $fillable = [
        'id',
        'nome',
      ];

    public function turmas()
    {
        return $this->belongsToMany('App\Models\Turma', 'turma_disciplina_visita')->withPivot('disciplina_id');
    }

}

// Class TURMA
class Turma extends Model
{

    protected $fillable = [
        'id',
        'nome',
        'curso_id',
    ];

    public function curso()
  {
      return $this->belongsTo('App\Models\Curso');
  }

}

// Class CURSO
class Curso extends Model
{

    protected $fillable = [
        'id',
        'nome',
    ];

    public function turmas()
  {
      return $this->hasMany('App\Models\Turma');
  }

}

// Class VISITACONTROLLER
class VisitaController extends BaseController
{

  public function list($request, $response)
  {
    $visitas = Visita::all(); // brings me the visita and the turma with its attributes
    $cursos = Curso::all(); // wanted to get cursos without needing this extra query which brings me all the cursos..

    return $this->view->render($response, 'Visitas/list.php', [
        'visitas' => $visitas,
        'cursos'  => $cursos,
    ]);

  }
}

// View LIST.PHP

// This way I get the turma.nome
foreach ($visita->turmas as $turma){
  echo $turma['nome'] . '<br>';

// This way I get the curso.nome
foreach ($visita->turmas as $turma){
  echo $cursos[$turma['curso_id']] . '<br>';

1 Answers1

1

have you tried to load your collection like this:

Visita::with('turmas.curso')->all();

And in your frontent you should be able to load your data like this:

foreach (($visita->turmas as $turma){
    $turma->curso->nome;
}

Hope this helps

Aubin
  • 87
  • 1
  • 5