So I'm currently practicing with Laravel, and running into a problem where the sql query is reading everything from my second table as an array, rather than the column it should be assigned to.
I have a packages table, and a resources table to fill those packages. Package name and price work fine, but when I need to read from resources, I get this:
[{"id":2,"resource":"Vegetarian menu","package_id":2,"created_at":"2022-06-18T19:34:48.000000Z","updated_at":"2022-06-18T19:34:48.000000Z"},{"id":3,"resource":"Standard Menu","package_id":2,"created_at":"2022-06-18T19:35:31.000000Z","updated_at":"2022-06-18T19:35:31.000000Z"}]
When it really should be just "Vegetarian menu", and "Standard Menu"
What am I doing wrong?
//package model
class Package extends Model { use HasFactory;
protected $fillable = ['name'];
public function resources()
{
return $this->hasMany(Resource::class);
} }
//package controller
class PackageController extends Controller {public function index(){
// SELECT * FROM packages
$packages = Package::with('resources')->get();
return view('service', compact('packages')); } }
//resource model
class Resource extends Model {
use HasFactory;
protected $fillable = ['package_id', 'resource'];
public function package()
{
return $this->belongsTo(Package::class);
} }
// UI Page
@foreach ($packages as $package)
<div ><!-- each child tile needs it's own parent -->
<article >
<figure >
<img src="https://bulma.io/images/placeholders/96x96.png" alt="">
</figure>
<p >{{ $package->name }}</p>
<h4 >£{{ number_format($package->cost) }}.00</h4>
<div >
<ul>
<li>{{ $package->resources }}</li>
</ul>
</div><!-- content -->
</article>
</div><!-- parent -->
@endforeach
CodePudding user response:
You are correctly getting what you are requesting. A collection of resources associated with every package.
[
{
"id":2,
"resource":"Vegetarian menu",
"package_id":2,
"created_at":"2022-06-18T19:34:48.000000Z",
"updated_at":"2022-06-18T19:34:48.000000Z"
},
{
"id":3,
"resource":"Standard Menu",
"package_id":2,
"created_at":"2022-06-18T19:35:31.000000Z",
"updated_at":"2022-06-18T19:35:31.000000Z"
}
]
If you want to limit the fields on the resource relation then you should modify your query as
class PackageController extends Controller {
public function index(){
// SELECT * FROM packages eager loads resource name and package_id
$packages = Package::with('resources:resource,package_id')->get();
return view('service', compact('packages'));
}
}
CodePudding user response:
you just need to loop through the related collection
@foreach ($packages as $package)
<div ><!-- each child tile needs it's own parent -->
<article >
<figure >
<img src="https://bulma.io/images/placeholders/96x96.png" alt="">
</figure>
<p >{{ $package->name }}</p>
<h4 >£{{ number_format($package->cost) }}.00</h4>
<div >
<ul>
@foreach ($package->resources as $r)
<li>{{ $r->resource }}</li>
@endforeach
</ul>
</div><!-- content -->
</article>
</div><!-- parent -->
@endforeach