I am doing a support system for courses and I am using the belongs for relationship, at the time of issuing the registration of students is not registering in the class and does not issue any error.
Codes
Model
<?php
namespace App;
use App\Turma;
use App\Trabalhos;
use InstagramAPI\Response\Model\Users;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $table = 'users';
protected $fillable = [
'name',
'email',
'password',
'gender',
'permission',
'status',
'telefone',
'celular',
'nascimento',
'endereco',
'cep'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token', 'rg', 'cpf'
];
public function trabalhos(){
return $this->belongsToMany(Trabalhos::class, 'alunos_trb', 'aluno_id',
'trabalho_id');
}
public function turma(){
return $this->belongsToMany(Turma::class, 'turma_usuarios',
'usuario_id', 'turma_id');
}
}
Controller
public function cadastro(Request $request){
$data = explode('/', $request->get('nascimento'));
$dataNascimento = $data[2].'-'.$data[1].'-'.$data[0];
Validator([
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'gender' => 'required',
'telefone' => 'required|char',
'celular' => 'required|char',
'nascimento' => 'required',
'endereco' => 'required',
'cep' => 'required|char',
'rg' => 'required|char',
'cpf' => 'required|char',
'turma' => 'required'
]);
// print_r($request->turma);
// die;
try{
DB::beginTransaction();
$aluno = new User();
$aluno->name = $request->name;
$aluno->email = $request->email;
$aluno->password = bcrypt($request->password);
$aluno->gender = $request->gender;
$aluno->telefone = $request->phone;
$aluno->celular = $request->celular;
$aluno->nascimento = $dataNascimento;
$aluno->endereco = $request->endereco;
$aluno->cep = $request->cep;
$aluno->rg = $request->rg;
$aluno->cpf = $request->cpf;
$aluno->save();
if(is_array($request->turma)){
foreach( $request->turma as $m){
$turma = Turma::find($m);
$aluno->turma()->attach($turma);
}
}
$aluno->save();
DB::commit();
return \Redirect::to('/alunos/lista');
}catch(\Expension $e){
DB::rollBack();
return \Redirect::to('/alunos/lista');
}
}