Simple question about Laravel and get() function

Asked

Viewed 36 times

2

Hello, I’ve been using Standard for some time now and I’m 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();

get-out():

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

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

1 answer

2


When you use the get, he executes the query which is stored in the Builder and it returns the values of this query.

When you don’t use the get, you just return an instance of Builder and with that, you can store in a variable and/or manipulate in any way you feel necessary.

Beyond the get, there are other functions also that perform the query and return some value to you as the function find or first.

Generally speaking, use the first if there is no business rule when performing a query, just stack the where and at the end add the get. Otherwise, store the instance of Builder in a variable and make appropriate checks.

Following example 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();

Browser other questions tagged

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