1
votes

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.

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().

1
Is $vehicles successfully set at all? In your controller, just return $vehicles;, what do you get? - Don't Panic
@Don'tPanic It is returning all required values. - Anon

1 Answers

3
votes

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

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.