Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

384
Views
RelationShip BelongsToMany Laravel - Only return withTimeStamps

I need your help.

I have next models:

class Store extends Model {
    public function categories()
    {
        return $this->belongsToMany(Category::class,'category_by_store','store_id','category_id')->withPivot('refIdInMyStore');
    }
}

class Category extends Model{
public function store()
    {
        return $this->belongsToMany(Store::class, 'category_by_store','category_id','store_id');
    }}

So, if I want to retrieve categories from a store I write:

$store = Store::find(1);
$categories = $store->categories()

But the response is: {"withTimestamps":false}

¿What is my mistake?

Thanks!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

It's because you are calling it as a function $store->categories(). Which would be similar to calling Categories::where('store_id', $id) without calling ->get() to execute the query.

You should call it as an attribute $categories = $store->categories instead.

There are many who are against not being explicit about the fact that you are executing a new query because the relationship looks like an attribute.

I have found that it's better for code clarity and likely performance to use the eager loading like this:

$store = Store::with('categories')->find(1);

I believe this clearly signals that you will be using the categories relationship.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!