0
I’m having a little problem, I have a relationship of course and student in the system.
I created a show function in the controller and wanted to make sure that when clicking on the details it showed all the students enrolled in a course. show in Cursocontroller
public function mostrar($id)
{
$alunos = Curso::whereHas('alunos')->with('alunos')->where('id', $id)->get();
return view('curso.mostrar', compact('alunos'));
}
And my show.blade.php
<div class="container">
<br>
<div class="pull-right">
<a class="btn btn-success" href="{{ action('CursoController@index') }}"> Voltar</a>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Nome</th>
<th>Cidade</th>
<th>Estado</th>
</tr>
</thead>
<tbody>
@foreach($alunos as $aluno)
<tr>
<td>{{$aluno->id}}</td>
<td>{{$aluno->nome}}</td>
<td>{{ $aluno->cidade }}</td>
<td>{{ $aluno->estado}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
The problem here is that it is returning the name of the course to the envés of the relation of students.
My course model is like this
class Curso extends Model
{
protected $fillable = ['professor_id', 'nome'];
public function professor()
{
return $this->belongsTo(\App\Professor::class);
}
public function alunos()
{
return $this->hasMany(\App\Aluno::class);
}
}
My student model is like this
class Aluno extends Model
{
protected $fillable = ['curso_id','nome','data_nascimento', 'cep', 'logradouro', 'numero', 'bairro', 'cidade', 'estado'];
public function curso()
{
return $this->belongsTo(\App\Curso::class);
}
}
Anyone can help?
In the end it was solved like this: Cursocontroller
public function mostrar($id)
{
$curso = Curso::findOrFail($id);
$alunos = $curso->alunos;
return view('curso.mostrar', compact('curso', 'alunos'));
}
And the route
Route::get('cursos/{id}/mostrar', 'CursoController@mostrar');
You can create a course method within the Student Model, and vice versa. This way, each student will have ->courses as well as each course will have ->students.
– David Dias