1
This is my View
:
<tbody>
@if(isset($pessoas))
@foreach($pessoas as $p)
<tr>
<td>{{$p->nome}}</td>
<td>{{$p->idade}}</td>
<td>{{$p->cidade->nome}}</td>
@endforeach
@endif
</tbody>
The Controller
passing the parameter people and returns to View
:
public function verPessoas()
{
$pessoas = Pessoa::all();
return view('verPessoas', compact('pessoas'));
}
Relationship in Model
Pessoa
public function cidade()
{
return $this->belongsTo('App\Cidade');
}
Relation in the Model "City"
public function pessoa()
{
return $this->hasMany('App\Pessoa');
}
This relationship is 1:N, where the table pessoas
receives the foreign key from cidade
(cidade_id
), being a city has several people, each person belongs to a city. When I try to access this View
get the error:
Trying to get property of non-object (View: C:\xampp\htdocs\projetos\PROJETO\resources\views\verPessoas.blade.php)
When I remove the line
<td>{{$p->cidade->nome}}</td>
Everything works normally, leading to believe that I am relating the models
wrong way and checked the tables of the bank and their respective values, everything is filled and working perfectly.
I would like to understand what causes this error and what the appropriate solution.
Possibly this is the problem, just remembering that the definition FK is only needed if it is not
tabela_id
, what may be what is happening.– Pliavi
@Pliavi yes, I will complement in the answer.
– Felipe Paetzold
my foreign key has the default name. I have tested the above suggestion but not solved it yet
– MarceloSnts
@Marcelosnts can show you how his
$fillable
?– Felipe Paetzold
@Felipe Paetzold Pessoa:
protected $fillable = array('nome', 'idade');
City:protected $fillable = array('nome');
– MarceloSnts
@Marcelosnts Put city_id in person fillable
– Felipe Paetzold
put, but still not working, continues the same error.
– MarceloSnts
@Marcelosnts strange, return this way to the view then
return view('verPessoas', ['pessoas' => $pessoas]);
, if it doesn’t work you can try to manipulate city as array<td>{{$p->cidade['nome']}}</td>
but apparently it’s all right– Felipe Paetzold
also did not work, the first suggestion showed the same error and the second left a blank field, however, displayed the other information in the same way when removing the
<td>{{$p->cidade->nome}}</td>
.– MarceloSnts
@Marcelosnts In the controller do a foreach of
$pessoas
and inside the loop usedd($pessoa->cidade)
and see what returns– Felipe Paetzold
@Felipe Paetzold, sorry, I ended up not testing this way because the solution proposed by Virgilio Novic solved my problem. I appreciate the help.
– MarceloSnts