简体   繁体   English

为foreach()提供了无效的参数

[英]Invalid argument supplied for foreach()

Newbie here. 新手在这里。 I've been working on a one to many relationship in Laravel 5.4. 我一直在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);
    }
}

Check array or object count before applying foreach loop. 在应用foreach循环之前,请检查数组或对象计数。 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

Check get results is not a blank $results != FALSE You can convert this snippet in laravel way 检查获取结果不是空白的$results != FALSE您可以以laravel方式转换此代码段

<?php
    if($user->states != FALSE){
        foreach ($user->states as $note){
            echo '<li>'.$note->name.'</li>';
        }
    }else{
        echo 'No Results Found!';
    }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM