Caio Kawasaki
Caio Kawasaki

Reputation: 2950

How to paginate objects from a relationship

How can i return this same query with pagination from the relacted produtos with categoria?

My Model DB:

Model DataBase

Config Model Eloquent categoria:

namespace App\Models;

class Categoria extends ModelDefault
{
    protected $table = 'categoria';

    public function produtos()
    {
        return $this->belongsToMany('App\Models\Produto', 'categoria_produto', 'categoria_id')->withTimestamps();
    }

}

Config Model Eloquent produto:

namespace App\Models;

class Produto extends ModelDefault
{
    protected $table = 'produto';

    public function categorias()
    {
        return $this->belongsToMany('App\Models\Categoria', 'categoria_produto', 'produto_id')->withTimestamps();
    }

    public function images()
    {
        return $this->hasMany('App\Models\ProdutoImagem','produto_id', 'id');
    }

}

My query to get produtos from categoria:

$produtosPorCategoria = Categoria::with(['produtos.images.image'])
        ->where('slug', $categoria_slug)
        ->ativo()
        ->first();
    dd($produtosPorCategoria);

Here you can see a printscreen from my returned array:

enter image description here

Upvotes: 1

Views: 33

Answers (1)

Michel Ayres
Michel Ayres

Reputation: 5985

If I understood what you need. you should try this

$produtosPorCategoria = Categoria::with(['produtos.images.image'])
    ->where('slug', $categoria_slug)
    ->ativo()
    ->first();

Should be

$produtosPorCategoria = Categoria::with(['produtos.images.image'])
    ->where('slug', $categoria_slug)
    ->ativo()
    ->first();

$produtosPorCategoria = $produtosPorCategoria->produtos()->paginate(5);

Upvotes: 1

Related Questions