I have a problem when I want to show data in a CRUD for users. The user table has the id of the teaching table as a foreign key. This is the User model:
class User extends Authenticatable{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'iddocente', 'email', 'rol', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function docente(){
return $this->belongsTo('App\Docente');
}
}
And this is the teaching model:
class Docente extends Model{
protected $fillable = [
'nip', 'nombres', 'apellidos', 'dui', 'nit', 'especialidad'
];
public function grados(){
return $this->belongsToMany('App\Grado');
}
public function asignaturas(){
return $this->belongsToMany('App\Asignatura');
}
public function users(){
return $this->hasMany('App\User');
}
}
In the controller I am trying to make the list of users show the teacher assigned to that user and according to some tutorials they do it with the function each () and implement it in this way:
public function index(){
$users=User::orderBy('id', 'ASC')->paginate(10);
$users->each(function($users){
$users->docente;
});
I have implemented it that way and I get an error in the index.blade.php view, which is where I want to show that table. The error is as follows:
(2/2) ErrorException Trying to get property of non-object
The view is as follows: index.blade.php
@extends('templates.main')
@section('title', 'Listado de Usuarios')
@section('content')
<a href="{{ route('usuarios.create') }}" class="btn btn-info">Registrar nuevo usuario</a><hr>
<table class="table table-condensed">
<thead>
<th>Docente</th>
<th>Correo electrónico</th>
<th>Rol</th>
<th>Acción</th>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td>{{ $user->docente->nombres }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->rol }}</td>
<td><a href="#" onclick="return confirm('¿Deseas eliminar este docente?')" class="btn btn-danger"><span class="glyphicon glyphicon- remove" aria-hidden="true"></span></a>
<a href="#" class="btn btn-warning"><span class="glyphicon glyphicon-wrench" aria-hidden="true"></span></a></td>
</tr>
@endforeach
</tbody>
</table>
@endsection