I have the following models, Item.php and Shipment.php set up. What I am trying to do is display the Item names, based on the shipment ID. I can access the shipments via $shipments = App\Shipment::where('id',4)->get(); but I am totally lost as to how to retrieve the item names, based on the Shipment model.
I am thinking something along the lines of $shipment->items()->getName or the like, but I cannot seem to wrap my head around it.
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
protected $fillable = ['name',
'description',
'category',
'condition'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function category() {
return $this->hasOne('App\Category');
}
public function shipments(){
return $this->belongsToMany('App\Shipment');
}
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Shipment extends Model {
protected $fillable = ['id',
'item_id',
'qty',
'user_id'
];
public function user(){
return $this->belongsTo('App\User');
}
public function items(){
return $this->hasMany('App\Item','id','item_id');
}
It's important to know what a certain method will return. If it is a collection or a single model instance. This for example returns a collection (even if it only has one model in it)
App\Shipment::where('id',4)->get();
Instead use first()
or just find()
to add a where clause for the id and then only return one:
App\Shipment::find(4);
With the relationship it's similar. Since items
is a hasMany relation, it will always return a collection. That means usually you will retrieve the items and loop over them:
foreach($shipment->items as $item){
echo $item->name;
}
Also note that there's a difference between $shipment->items()
and $shipment->items
.
For more on that, read this answer.