我正在尝试从控制器传递的视图中获取值。 在我的控制器中,我的语法是:
public function index()
{
$vehicles=vehicles::orderBy('created_at', 'desc')->get();
// return $vehicles;
$ad=ads::orderBy('views','desc')->get();
// return $ad;
foreach ($ad as $ads) {
# code...
$popularvehicle[]=vehicles::where('id',$ads->id)->get();
// echo $popularvehicle;
}
return view('index',compact('vehicles','popularvehicle'));
}
在我的观点中,我试过以下内容:
@foreach($popularvehicle as $popularvehicle)
{{$popularvehicle->vname}}
@endforeach
它给出了Undefined property: Illuminate\Database\Eloquent\Collection::$vname
我也试过{!!$popularvehicle['vname']!!}
。但它会像未定义的索引一样抛出错误。
当我回显{!!$popularvehicle!!}
时,它会提供所需的所有值,例如[{"id":3,"vname":"Pulsar","lotno":"Ba 25 Pa","engine":"150","mileage":"35","kilometers":25000,"price":"120000","negotiable":"Yes","vcondition":"New","used":"3 month","manufacture_year":"2015","description":"Almost New","Company_cid":1,"Users_id":1,"Vehicle_Type_id":1,"created_at":"2017-01-12 15:08:41","updated_at":"2017-01-12 15:08:41"}].
如何获取$popularvehicle
的值?谁能帮我?将数组转换为对象有助于解决此问题。如果是,我该怎么办?
答案 0 :(得分:1)
错误是因为->
试图指向对象$popularvehicles[]
的属性是一个数组:
$ads=ads::orderBy('views','desc')->get();
foreach ($ads as $ad) {
$popularvehicles[]=vehicles::where('id',$ad->id)->get()->toArray();
}
然后,
@foreach($popularvehicles as $popularvehicle)
@foreach($popularvehicle as $vehicle)
{{$vehicle['vname']}}
@endforeach
@endforeach
请注意对命名约定所做的更改。此外,模型名称最好是单数。
答案 1 :(得分:0)
考虑复数名称
$popularvehicles = array();
foreach ($ad as $ads) {
$popularvehicles[]=vehicles::where('id',$ads->id)->get();
}
return view('index',compact('vehicles','popularvehicles'));
并在视图中使用
@foreach($popularvehicles as $popularvehicle)
{{$popularvehicle->vname}}
@endforeach
答案 2 :(得分:0)
试试这个:
控制器:
$popularvehicle = vehicles::where('id',$ads->id)->get();
// If you use $popularvehicles[] then you have to use one extra foreach() to retrieve the columns
查看:
@foreach($popularvehicle as $vehicle)
{{$vehicle->id}} // for id
{{$vehicle->vname}} // for name
@endforeach
答案 3 :(得分:0)
试试这个:
public function index()
{
$vehicles = vehicles::orderBy('created_at', 'desc')->get();
// return $vehicles;
$ads = ads::orderBy('views','desc')->get();
// return $ad;
foreach ($ads as $ad) {
# code...
$popularvehicles[]=vehicles::find($ad->id);
}
return view('index',compact('vehicles','popularvehicles'));
}
在你看来:
@foreach($popularvehicles as $popularvehicle)
{{$popularvehicle->vname}}
@endforeach