Method on model to get unique element from its pivot table
A product can be owned by different customers over time. I have three tables to represent this:
products
customers
customers_products
The pivot table (customers_products) has two additional columns: valid_from and valid_till, which are datetime fields. The timespan inbetween these fields reflects the period the product is owned by a particular customer.
When showing a list of all products, I need to show the current owner (customer) only. How would I set up a method on my Product model, so that in my Controller I could do Product::with('currentOwner')->get() and in my Views I could do $product->currentOwner->companyName?
public function current_owners ()
{
// Assuming there is a customers() method defining the many to many relationship
// with customers
return $this->customers()
->where('pivot.valid_from', '<', \Carbon::now())
->where('pivot.valid_till', '>', \Carbon::now());
}
But this will still return a collection. Hence the s in current_owners. Create an accessor to return an object :
public function getCurrentOwnerAttribute ()
{
return $this->current_owners->first();
}
Thanks for the fast reply!
It makes sense and it works. I do have to change the last bit of code you posted into this:
$product->current_owner['companyName'];
I'm not sure why $product->current_owner isn't an Eloquent model. This is what I do in my Controller:
public function index()
{
$products = Product::with('current_owners')->get();
return view('products.list', compact('current_owners'));
}
Like I said, it works, but I'd like to understand why $product->current_owner->companyName doesn't work while $product->current_owner['companyName'] does.
Yeah, that error was introduced when converting my actual code to something I could post in this forum. In my working code that wasn't the issue.
The issue was, that I currently have products that don't have an owner. That's why $product->current_owner->companyName caused an error (trying to get property of non-object).