Reputation: 147
Newbie here. I've been working on a one to many relationship in Laravel 5.4. I'm working on reading the relationship between User and State. I keep getting this error. I have data in the tables. Here is the view:
@foreach ($user->states as $note)
<li>{{ $note->name }}</li>
@endforeach
Here is the User model:
class User extends Model
{
use SoftDeletes;
public function state(){
return $this->belongsTo(State::class);
}
public function role(){
return $this->belongsTo(Role::class);
}
public function district(){
return $this->belongsTo(District::class);
}
Here is the State model:
class State extends Model
{
protected $fillable = [
'name'
];
public function users(){
return $this->hasMany(User::class);
}
}
Upvotes: 0
Views: 1509
Reputation: 3965
Check array or object count before applying foreach loop. It is really a bad practice of using loop without checking the array count.
@if(isset($user->states) && count($user->states) > 0)
@foreach ($user->states as $state)
<li>{{ $state->name }}</li>
@endforeach
@else
No Records Found
@endif
Upvotes: 1
Reputation: 1527
Check get results is not a blank $results != FALSE
You can convert this snippet in laravel way
<?php
if($user->states != FALSE){
foreach ($user->states as $note){
echo '<li>'.$note->name.'</li>';
}
}else{
echo 'No Results Found!';
}
?>
Upvotes: 0