Reputation: 13
I'm new to laravel and i'm having a hard time displaying the items of the package that i have selected in my blade view. I can display all packages in one blade view. The goal is to let me view the contents of a package if i click it on the blade view.
PackageItems Table
id | package_id | item_id | qty
package_id
is a foreign key from the packages
table and item_id
is from the items
table
Here's how i fetch the data:
Controller
public function showPackageItems($id)
{
$package = Package::find($id)
->with('packageitems')
->where('id', '=', $id)
->get();
return view('admin.packages.show')->with('package', $package);
}
Package Model
public function packageItems()
{
return $this->hasMany(PackageItem::class, 'package_id') ;
}
PackageItem Model
public function package()
{
return $this->belongsTo(Package::class,'package_id') ;
}
showItems Blade view
@foreach($package as p)
<td>{{$p->packageItem->item_id}}</td> //error
<td>{{$p->qty}}</td> //error as well
@endforeach
I already tried to dd($package) and i got the correct results. My problem is how do i display it on my blade view.
Upvotes: 1
Views: 7352
Reputation: 1763
Try this
Controller
public function showPackageItems($id)
{
$package = Package::find($id)
->with('packageItems')
->where('id', $id)
->first();
return view('admin.packages.show', compact('package'));
}
Blade file
{{ $package->id }} //you can access package instance like that.
//for packageItems
@foreach($package->packageItems as $p)
<td>{{ $p->item_id }}</td>
<td>{{ $p->qty }}</td>
@endforeach
Upvotes: 1
Reputation: 1932
Change your code on how to retrieve the records
using find and get is different: the difference of find and get in Eloquent
Also you need to get the packageitems first
public function showPackageItems($id)
{
$package = Package::with('packageitems')
->where('id', '=', $id)
->get();
return view('admin.packages.show')->with('package', $package);
}
Upvotes: 0
Reputation: 134
In Controller
public function showPackageItems($id)
{
$package = Package::with('packageItems')
->where('id', '=', $id)
->get();
return view('admin.packages.show')->with('package', $package);
}
In blade
@foreach($package as $p)
<td>{{$p->packageItem->item_id}}</td> //error
<td>{{$p->qty}}</td> //error as well
@endforeach
Upvotes: 1