I'm having a little problem, I have a course and student relationship in the system.
I created a show function in the controller and wanted to make clicking on the details show all students enrolled in a course. show on CourseController
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 course name instead of the student list.
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);
}
}
Can anyone help?
In the end it was solved like this: CourseController
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');