Using pluck laravel eloquent

0

I want to call a method of my laravel driver to return a JSON with the data that a DDBB. I have a Produtos table with the fields:

  

id, name, idCategoria, idGenero, stock

A table Category with:

  

id, name, created

And a Genre table with:

  

id, name, created

In the product model I have added the following functions:

public function categoria()
    {
        return $this->belongsTo(Categoria::class, 'idCategoria');
    }
    public function genero()
    {
        return $this->belongsTo(Genero::class, 'idGenero');
    }

In the category model and in the gender model I have added:

public function productos()
    {
        return $this->hasMany(Productos::class);
    }

The fact is that I want you to show me all the fields in the product table with the 'idCategoria' and 'idGenero' replaced by the name of their category and corresponding gender. I'm trying this:

public function index_front() {
        $products = Productos::with('categoria')->get()->pluck('id', 'nombre','categoria.nombre', 'stock');
        return json_encode($products);

    }

But I can not make him show me what I need.

    
asked by Ricardo Alvarado 08.05.2018 в 17:02
source

3 answers

0

I recommend you implement the Eloquent: API Resources .

1.- In console php artisan make:resource ProductoResource

This will generate the class App\Http\Resources\ProductoResource

2.- Modify this file located in app / Http / Resourses / ProductoResource.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ProductoResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        // return parent::toArray($request); // Comentá esta línea
        return [
            'id' => $this->id,
            'nombre' => $this->nombre,
            'categoria' => $this->categoria->nombre,
            'stock' => $this->stock,
        ];
    }
}

3.- In the controller do the following

public function index_front() {
    $products = Productos::all();
    return \App\Http\Resources\ProductoResource::collection($products);
}

You have endless options using the Api Resources, especially if you need json answers. You do not need to do json_encode (). Read the documentation well and you will be able to get the most out of this Laravel functionality.
You can also page results! there are some tutorials on youtube about it.
Greetings

    
answered by 09.05.2018 / 17:12
source
0

Simply use a select and put the 2 relations in the with

public function index_front() {
        $products = Productos::select('productos.*', 'categoria.nombre as categoria', 'genero.nombre as genero')->with(['categoria', 'genero'])->get();
        return json_encode($products);
    }
    
answered by 08.05.2018 в 17:39
0

in the part of the query place the with

$consulta=Produtos::with('idCategoria_pk','idGenero_pk')->get();

in the Produtos model place the following

funcion public function idCategoria_pk()
    {
        //archivo de modelo y el campo foreign_key 
        return $this->belongsTo('App\Categoria','idCategoria');   
    } 
funcion public function idGenero_pk()
    {
        //archivo de modelo y el campo foreign_key 
        return $this->belongsTo('App\Genero','idGenero');   
    } 

and in the view place the following

@foreach($consultaas $lists)
                    <td class="col1">{{ $lists->descripcion }}</td>

                    {{$lists->idCategoria_pk->nombre}}  
                    {{$lists->idGenero_pk->nombre}}          

                    </td>
            @endforeach
    
answered by 08.05.2018 в 17:51