Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

roggel's avatar
Level 13

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?

0 likes
4 replies
pmall's avatar
pmall
Best Answer
Level 56

By defining another relationship ?

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

Then this should work :

$product->current_owner->companyName;
1 like
roggel's avatar
Level 13

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.

pmall's avatar

You pass a $current_owners var to your view whereas it is not defined. It should be

public function index()
{
    $products = Product::with('current_owners')->get();
    return view('products.list', compact('products'));
}
roggel's avatar
Level 13

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).

Got that fixed now. Thanks for the help!

Please or to participate in this conversation.