• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

316
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!

about 3 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.

about 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error