【问题标题】:Invalid argument supplied for foreach(). Laravel为 foreach() 提供的参数无效。拉拉维尔
【发布时间】:2017-01-13 16:35:41
【问题描述】:

我试图从一对一的关系中获得价值。我的模型是用户和车辆。一个用户可以拥有多辆车,但一辆车只能拥有一个用户。我的观点有误:

我认为 foreach() 中的参数无效。

以下是我的语法。谁能帮帮我?

//users:
class users extends Model
{
    protected $fillable = ['fname','lname','address','contact','shop_name','email','username','password'];
    public function vehicles() {
        return $this->hasOne('App\vehicles');
    }
}

//vehicles:
class vehicles extends Model
{
    protected $fillable = ['vname','lotno','engine','mileage','kilometers','features','price','negotiable','vcondition','used','manufacture_year','description','Company_cid','Sellers_sid','Vehicle_Type_id'];    
    public function users() {
        return $this->belongsTo('App\users');
    }
}

控制器

public function show($id)
{
    $vehicles=vehicles::findorfail($id);
    return view('Bike.show',compact('vehicles'));
}

查看我试图从哪里获得用户的价值。

<tr>
<td><b>Contact No:</b></td>
 <td>                               
   @foreach($vehicles->users as $users)
    {{$users->contact}}
   @endforeach
</td>
</tr>

我不知道我哪里做错了。它显示错误“为 foreach() 提供的参数无效。

【问题讨论】:

  • $vehicles 设置成功了吗?在您的控制器中,只需 return $vehicles;,您会得到什么?
  • @Don'tPanic 它正在返回所有必需的值。

标签: php laravel laravel-5.2 information-retrieval


【解决方案1】:

foreach() 要求参数是集合或数组。由于车辆只属于一个用户,$vehicles-&gt;users 不会提供集合。你实际上并不需要一个 foreach 循环。 $vehicle-&gt;users-&gt;contact 可以。

注意:如果一个用户可以拥有多辆汽车,则关系应该是:

return $this->hasMany('App\Vehicle');

还要注意命名约定:模型名称为单数,如果是 hasOne 关系,则始终使关系单数,例如 user() 而不是 users(),如果是 hasMany,则使其复数。

【讨论】:

  • dd($vehicles) 看看它提供了什么
  • vehicles {#190 ▼ #fillable: array:15 [▶] #connection: null #table: null #primaryKey: "id" #keyType: "int" #perPage: 15 +incrementing: true +timestamps: true #attributes: array:17 [▶] #original: array:17 [▶] #relations: [] #hidden: [] #visible: [] #appends: [] #guarded: array:1 [▶] #dates: [] #dateFormat: null #casts: [] #touches: [] #observables: [] #with: [] #morphClass: null +exists: true +wasRecentlyCreated: false }
  • @foreach($vehicles as $vehicle) {{$vehicle-&gt;users-&gt;contact}} @endforeach 但我想知道$vehicles=vehicles::findorfail($id); 提供收藏。
  • 还是一样。当我尝试在控制器中返回 $vehicles->users 时,它显示为空。我想知道它是否导致了问题。
猜你喜欢
  • 1970-01-01
  • 2016-02-06
  • 2011-05-17
  • 2011-02-07
相关资源
最近更新 更多