Simple question about Laravel and get () function

2

Hello, I have been using laravel for some time and I am familiar with the framework, but I would like to know the real need to use the get () method when calling a class. For example:

Using get ():

$pessoa = \App\Pessoas::where('ID_CD_TIPOPESSOA',3)->where('IN_STATUS',1)->get();

without get ():

$pessoa= \App\Pessoas::where('ID_CD_TIPOPESSOA',3)->where('IN_STATUS',1);

What would be the difference between using get () and not using?

    
asked by anonymous 24.09.2018 / 16:57

1 answer

2

When you use get , it executes the query that is stored in the instance of Builder and it returns the values of that query.

When you do not use get , you just return an instance of Builder and with that, you can store in a variable and / or manipulate as you see fit.

In addition to get , there are other functions that also execute query and return some value such as the find or first function.

In general, use the first one if there is no business rule when making a query, just stack where and at the end add get . Otherwise, store the Builder instance in a variable and perform the checks.

Here is a code for the second case:

// Prepara uma query de base
$query = \App\Pessoas::where('ID_CD_TIPOPESSOA', 3)->where('IN_STATUS',1);

// Caso tenha um status que precise ser adicionado dinâmicamente
if($request->has('status_amais')
    $query->where('IN_STATUS', $request->input('status_amais'));

// Depois realiza a consulta
$results = $query->get();
    
25.09.2018 / 00:16