Laravel - How to pick, manipulate and change Lengthawarepaginator items

Asked

Viewed 734 times

1

Good night,

I need to take the database data and make a certain change in the return using php before returning the data.

I will not paste the real example, because it is very complex and would end up disturbing the understanding. I will create just an example to explain what I need.

I get the BD data using:

$dados = \App\Teste::select('id', 'valor')->paginate();

I need to use a foreach() to make a certain change. But with paginate() I have to use a function to pick up the items. Different than what you would have done if you’d used get()

$itens = $dados->getItems();
$novosValores = [];
$novoValor = new \stdClass();
foreach($items as $item){
    $novoValor->id = $item->id
    $novoValor->valor = $item->valor + 1;
    array_push($novosValores, $novoValor);
}

This way the array $newValues contains the changed values and now I need to replace the $dice for them. In the class documentation I found no method that could do this. Type a setItems(). There is no such function. But I believe there must be some way. I just don’t know which.

  • It’s a pagination data with the paginated data. If the change is just a sum of 1 in value you can do this in SQL itself, what you want!

  • I don’t know if I understood the question correctly, but maybe Mutators will solve the question ? You can manipulate and create attributes to a model. https://laravel.com/docs/5.8/eloquent-mutators

  • @Virgilionovic as I said before, this is just a simplified example to explain my need. What I need to do goes far beyond just adding +1 and as I could not solve with sql I am manipulating the data with php.

  • So it gets complicated if I give you a correct opinion about it, @Brunopassos, you could explain a little bit about it.

1 answer

1


I was able to solve by creating a new Lengthawarepaginator object and putting in it the data that was changed.

I found the example in https://stackoverflow.com/questions/37102841/laravel-change-pagination-data

Follow below as you would for my example:

$novosDados = new \Illuminate\Pagination\LengthAwarePaginator(
                $novosValores,
                $dados->total(),
                $dados->perPage(),
                $dados->currentPage(), [
                    'path' => \Request::url(),
                    'query' => [
                        'page' => $dados->currentPage()
                    ]
                ]
            );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.