Function extension on the Laravel

Asked

Viewed 186 times

3

I’m using the Laravel 5.3 and apparently I have a Controller calling the function:

(new AnuncioRepository())->getListagemAnuncios()

and the SQL for that is:

return DB::select('
            SELECT
                anuncio.id,
                cliente.nome AS "cliente",
                anuncio_area.nome AS "area",
                DATE_FORMAT(anuncio.data_inicio, "%d/%m/%Y") AS "inicio",
                DATE_FORMAT(anuncio.data_fim, "%d/%m/%Y") AS "fim",
                CONCAT(DATE_FORMAT(anuncio.hora_exibicao_inicio,"%H:%i"),
                    " - ",DATE_FORMAT(anuncio.hora_exibicao_fim,"%H:%i")) AS "horario",
                anuncio.valor,
                anuncio.ativo
            FROM
                anuncio
                RIGHT JOIN anuncio_area ON (anuncio_area.id = anuncio.id_anuncio_area)
                RIGHT JOIN cliente ON (cliente.id = anuncio.id_cliente)
            WHERE anuncio.ativo != "x"
                  AND anuncio.deleted_at is null
            ORDER BY anuncio.id DESC
        ');

What I wanted to do was extend a counter function in the repository for example:

(new AnuncioRepository())->getListagemAnuncios()->count();

And he counted the records that the SQL returned, how can I do it?

  • If you do DB::select('
 SELECT
 ...
 ')->count(); it does not return the number of rows?

1 answer

2


Use the classe Collection as follows:

$result = DB::select('
            SELECT
                anuncio.id,
                cliente.nome AS "cliente",
                anuncio_area.nome AS "area",
                DATE_FORMAT(anuncio.data_inicio, "%d/%m/%Y") AS "inicio",
                DATE_FORMAT(anuncio.data_fim, "%d/%m/%Y") AS "fim",
                CONCAT(DATE_FORMAT(anuncio.hora_exibicao_inicio,"%H:%i"),
                  " - ",DATE_FORMAT(anuncio.hora_exibicao_fim,"%H:%i")) AS "horario",
                anuncio.valor,
                anuncio.ativo
            FROM
                anuncio
                RIGHT JOIN anuncio_area ON (anuncio_area.id = anuncio.id_anuncio_area)
                RIGHT JOIN cliente ON (cliente.id = anuncio.id_cliente)
            WHERE anuncio.ativo != "x"
                  AND anuncio.deleted_at is null
            ORDER BY anuncio.id DESC
        ');

return collection($result);

with this setting has class object Collection with the methods implemented, for example the method Count. In that link is the method list that can be used. To show now all records use all().

How to use:

$result = (new AnuncioRepository())->getListagemAnuncios();
$result->count(); //quantidade de registros retornados
$result->all(); //os registros

References:

  • 1

    Thank you very much! question answered

Browser other questions tagged

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