Query eloquent two tables


I have a table of products that has the fields:


id, name, price, category_id

And I have the category table with the fields:


id, name

I am trying to make it return all the fields in the product table and instead of showing me the id, show me the name of the category. I would do it with SQL but not with eloquent.

EDIT: The purpose is to return a json with all the data of the products and the id category replaced with the name, since it is an API with laravel

asked by Ricardo Alvarado 07.05.2018 в 19:21

2 answers


you can in the model Categoria (assuming that it is called), create the   next method

In this first one we have the relation hasMany() because it is understood that a category has many products associated with it

public function productos()
   return $this->hasMany(Producto::class);

It is obvious that you will have to put where I put Producto::class the name that you gave to your model where you manage the table products

Later in the model Producto , do the following

In this part I use the relation belongsTo() because it is understood that a product belongs to a category

public function categoria()
   return $this->belongsTo(Categoria::class);

I explain.

To access these values, the following is done in the view

@foreach($productos as $producto)
    {{ $producto->nombre }}
    {{ $producto->precio }}
    {{ $producto->categoria->name }}

Please note the categoria->name refers to the categoria method and the categoria table and the name of that table

Here the source of official consultation, the Laravel documentation link

answered by 07.05.2018 / 19:37

I finally got it that way

$products = Productos::join('Categorias','idCategoria', '=', 'Categorias.id')->select('Productos.id','Productos.nombre','Categorias.nombre as NombreCategoria')->get();

Although I have not managed to understand very well how to use 'belongsto' and 'hasmany' to make this query ...

EDIT: Finally, based a little on Alfredo's response, I managed to show him Adding this to the product model:

public function categoria()
        return $this->belongsTo(Categoria::class, 'idCategoria');

And call it like that from the controller's method:

public function index_front() {
        $products = Productos::with('categoria')->get();
        return json_encode($products);

The only problem is that it shows me all the category data within an array in the answer and I just wanted the name ...

answered by 08.05.2018 в 01:28