How to use the Laravel Pagination feature with queries in raw format DB :: select ()

0

To get some information from the database in some moments is simpler to make a query with raw sql than to use several models, maps functions and a touch of magic to reach the same goal, however the problem of using a raw querie or a raw expression with ease we have to use the DB::select() function and exactly this easiness that creates a problem that the return of the data is not compatible with the function of Laravel called pagination or Database Pagination that is already ready with the framework, in my case I tried to use it as follows in my controller :

$sql = "SELECT * FROM CLIENTES CL, PEDIDOS PD WHERE PD.ID_CLIENTE = CL.ID";

public function obterDados(){
    return DB::select($sql)->simplePaginate(10);
}

Then the result returned is the error below:

Symfony\Component\Debug\Exception\FatalThrowableError (E_ERROR) "Call to a member function simplePaginate() on array"

So how to use DB :: select () with the pagination function of the Laravel framework?

    
asked by anonymous 01.08.2018 / 17:16

1 answer

0

The answer is as follows, to use the method simplePaginate() it is necessary for my function obterDados() to return an object Builder and not an object array because the is the Builder object that contains the simplePaginate () method.

The only way I found to use the pagination of the framework without changing the querie SQL was to create a view in the database . This way I could create a template to access this view , so I was able to solve my problem and the function in my controller looks like this:

$sql = "SELECT * FROM CLIENTES CL, PEDIDOS PD WHERE PD.ID_CLIENTE = CL.ID";

public function obterDados(){
    return ViewPedidosClientes::simplePaginate(15);
}
    
01.08.2018 / 17:16