Reputation: 543
I'm trying to fetch values at view passed from controller. In my controller my syntax are:
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'));
}
In my views i've tried following:
@foreach($popularvehicle as $popularvehicle)
{{$popularvehicle->vname}}
@endforeach
It gives an error of Undefined property: Illuminate\Database\Eloquent\Collection::$vname
I've also tried {!!$popularvehicle['vname']!!}
. But it throws error like undefined index.
When i echo {!!$popularvehicle!!}
it gives all the values required like [{"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"}].
How can i fetch the values of $popularvehicle
? Can anyone help me? Will converting array to object help solve this problem. If yes, how can i do so?
Upvotes: 0
Views: 92
Reputation: 9465
Try this:
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'));
}
And in your view:
@foreach($popularvehicles as $popularvehicle)
{{$popularvehicle->vname}}
@endforeach
Upvotes: 0
Reputation: 3266
The error is because ->
is trying to point to the property of object $popularvehicles[]
is an array:
$ads=ads::orderBy('views','desc')->get();
foreach ($ads as $ad) {
$popularvehicles[]=vehicles::where('id',$ad->id)->get()->toArray();
}
and then,
@foreach($popularvehicles as $popularvehicle)
@foreach($popularvehicle as $vehicle)
{{$vehicle['vname']}}
@endforeach
@endforeach
Note the changes made for naming conventions. Also, Model name is good to be singular.
Upvotes: 1
Reputation: 26258
Try this:
Controller:
$popularvehicle = vehicles::where('id',$ads->id)->get();
// If you use $popularvehicles[] then you have to use one extra foreach() to retrieve the columns
View:
@foreach($popularvehicle as $vehicle)
{{$vehicle->id}} // for id
{{$vehicle->vname}} // for name
@endforeach
Upvotes: 0
Reputation: 34914
Consider plural name
$popularvehicles = array();
foreach ($ad as $ads) {
$popularvehicles[]=vehicles::where('id',$ads->id)->get();
}
return view('index',compact('vehicles','popularvehicles'));
And use in view
@foreach($popularvehicles as $popularvehicle)
{{$popularvehicle->vname}}
@endforeach
Upvotes: 0