简体   繁体   中英

How to display on blade view the contents of a selected id? Laravel

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.

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 

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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM