Extension of function in laravel

3

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

(new AnuncioRepository())->getListagemAnuncios()

and the SQL for this 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 to extend a counter function in repository to example :

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

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

    
asked by anonymous 04.01.2017 / 13:44

1 answer

3

Use 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);

This setting has the object collection with the implemented methods, for example the count . In this link is the list of methods that can be used. To now show all logs use all () .

How to use:

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

References:

04.01.2017 / 14:01