为 foreach() 提供的参数无效。Laravel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41639340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:07:09  来源:igfitidea点击:

Invalid argument supplied for foreach(). Laravel

phplaravellaravel-5.2information-retrieval

提问by Anon

I'm trying to get value from one to one relation. My models are Users and Vehicles. One user can have muliple vehicles but one vehicles can have only one user. I'm getting error in my view:

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

invalid argument in foreach() in my view.

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

Following is my syntax. Can any one help me?

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

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

Controller

控制器

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

View where I'm trying to get value of user.

查看我试图获得用户价值的地方。

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

I don't know where i did wrong. It shows an error `Invalid argument supplied for foreach().

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

回答by Sanzeeb Aryal

foreach()requires an argument to be a collection or array. Since a Vehicle belongsTo only one user, $vehicles->userswon't give a collection. You don't really require a foreach loop there. $vehicle->users->contactwill do.

foreach()需要一个参数是一个集合或数组。由于一个 Vehicle 只属于一个用户,所以$vehicles->users不会给出一个集合。你并不真正需要一个 foreach 循环。$vehicle->users->contact会做。

Note: If One user can have multiple vehicles, the relation should instead be:

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

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

Also note the naming conventions: Model name to be singular, if it is hasOne relation always make the relation singular e.g user()not users()and if it is hasMany make it plural.

还要注意命名约定:模型名称是单数,如果是 hasOne 关系总是将关系设为单数,例如user()not users(),如果是 hasMany则设为复数。