0
I am trying to list an association table, in my case it is the class table, which associates employees (teachers) and students.
I did a good search before posting this question but could not solve the problem.
model employee
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\Pivot;
class Funcionario extends Authenticatable
#class Funcionario extends Model
{
use Notifiable;
protected $fillable = [
'login','password','nome', 'sobrenome', 'nome_completo','rg','cpf','email',
'cargo', 'data_registro','data_nascimento', 'nivel_acesso', 'sexo',
'telefone','telefone2',
'cidade','endereco','bairro','numero','cep','estado_id','escola_id',
];
protected $hidden = [
'password','remember_token'
];
public function estado()
{
return $this->belongsTo('App\Models\Estado');
}
public function escola()
{
return $this->belongsTo('App\Models\Escola');
}
public function alunos()
{
return $this->belongsToMany('App\Models\Aluno','turmas','funcionario_id','aluno_id')
->withPivot('serie','nome','nivel','professor','periodo','id');
}
}
student model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Aluno extends Authenticatable{
use Notifiable;
protected $fillable = [
'login','password','nivel_acesso','nome','sobrenome','nome_completo','certidao_nascimento',
'data_nascimento','data_matricula','naturalidade','ra','rm','raca','cor','rg','cpf',
'email','sexo',
'telefone','telefone2',
'cidade','endereco','bairro','numero', 'cep',
'estado_id','escola_id',
];
protected $hidden = ['password','remember_token'];
public function responsaveis()
{
return $this->belongsToMany('App\Models\Responsavel');
}
public function escola()
{
return $this->belongsTo('App\Models\Escola');
}
public function estado()
{
return $this->belongsTo('App\Models\Estado');
}
public function necessidades()
{
return $this->hasMany('App\Models\Necessidade');
}
public function funcionarios()
{
return $this->BelongsToMany('App\Models\Funcionario','turmas','aluno_id','funcionario_id')
->withPivot('serie','nome','professor','periodo','nivel');
}
}
Migration association
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTurmaTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('turmas', function (Blueprint $table) {
$table->increments('id');
$table->integer('aluno_id')->unsigned()->nullable();
$table->integer('funcionario_id')->unsigned()->nullable();
$table->string('nome');
$table->string('nivel');
$table->string('serie');
$table->string('professor');
$table->string('periodo');
$table->integer('escola_id')->unsigned();
#$table->primary(['aluno_id','funcionario_id']);
$table->foreign('aluno_id')
->references('id')->on('alunos')
->onDelete('cascade')
->onUpdate('cascade');
$table->foreign('funcionario_id')
->references('id')->on('funcionarios')
->onDelete('cascade')
->onUpdate('cascade');
$table->foreign('escola_id')
->references('id')->on('escolas')
->onDelete('cascade')
->onUpdate('cascade');
$table->timestamps();
$table->engine = 'InnoDB';
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('turma');
}
}
controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Funcionario;
use App\Models\Aluno;
use Auth;
use DB;
class TurmaController extends Controller
{
/**
* construtor com auth
*/
public function __construct(){
$this->middleware('auth:funcionario');
}
public function getlistar(){
#$professores = Funcionario::all()->first();
$professores = Funcionario::with('alunos')->get();
return view('turma.index',compact('professores'));
}
public function getAdicionar(){
$professores = Funcionario::where('cargo', '=', 'Professor', 'AND','escola_id','=',Auth::user()->escola_id)->get();
$alunos = Aluno::where('escola_id','=',Auth::user()->escola_id)->get();
return view('turma.adicionar', compact('professores','alunos'));
}
public function postCreate(Request $req){
$func = Funcionario::find(Auth::user()->id);
$aluno = $req->aluno;
$func->turma()->attach($aluno,[
'nome'=>$req->nome,
'nivel'=>$req->nivel,
'serie'=>$req->serie,
'professor'=>$req->professor,
'periodo'=>$req->periodo,
'escola_id'=>$req->escola_id,
]);
}
}
view
<!-- EXTENDS LAYOUT -->
@extends('layout.app')
<!-- TITULO -->
@section('titulo','Home')
<!-- CONTEUDO -->
@section('conteudo')
<div class="container">
@if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
@endif
<h3 align="center">Lista de turmas</h3>
<br>
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">nome</th>
<th scope="col">nivel</th>
<th scope="col">serie</th>
<th scope="col">professor</th>
<th scope="col">periodo</th>
<th scope="col">Ação</th>
</tr>
</thead>
<tbody>
@foreach($professores as $value)
<tr scope="row">
{{-- para 1 so
@foreach($professores->alunos as $aluno)
<td>{{ $value->pivot->nome }}</td>
@endforeach--}}
<td>{{ $value->alunos()->alunos->nome }}</td>
{{-- <td>{{ $value->pivot->nivel }}</td>
<td>{{ $aluno->pivot->serie }}ª</td>
<td>{{ $aluno->pivot->professor }}</td>
<td>{{ $aluno->pivot->periodo }}</td> --}}
<td class="row">
<a class="" href="{{ route('turma.atualizar',$value->id) }}">Editar</a>
<a class="" href="{{ route('turma.mostrar',$value->id) }}">Mostrar</a>
<a class="" href="{{ route('turma.deletar',$value->id) }}">Deletar</a>
</td>
</tr>
@endforeach
</tbody>
</table>
<a id="" class="btn btn-raised btn-secondary" href="{{ route('turma.adicionar') }}">ADICIONAR</a>
</div>
@endsection
if I use the first() that picks up only 1 works (I left commented the first one) and I’m using get because I want to show all classes in the pivot table.
$value->alunos()->alunos->nome
looks like you’re calling the name of an array? Ali shouldn’t be a First or iterate on it?– David Dias
first() works, but I need to show all the classes in a list. how would you do that? could you give an example please
– Luiz Henrique
You need to iterate OR use some method that does something in the implode style. See tip 7 of this link http://laraveldaily.com/10-less-known-but-awesome-laravel-collections-methods/
– David Dias
use a foreach to iterate and display the results.
– Luís Almeida
agree use a foreach
– Marcos Brinner
Problem solved with foreach. obg
– Luiz Henrique