Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

380
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda