Search code examples
phplaravelforeachlaravel-5.3

Invalid argument supplied for foreach()


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);
    }
}

Solution

  • 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!';
        }
    ?>