Is it correct to use get/set and other methods in the model of the Laravel?

Asked

Viewed 164 times

0

Example:

In the model:

public function getProduct()
{
  return $this->where('price',100)->get();
}

public function checkProduct($price)
{
  if($price > 100){
     return $price;
  }
}

On the controller:

$product = new Product();
$product->getProduct();
$product->checkProduct();

1 answer

0


is not incorrect, but there are ways that the eloquent itself delivers:

  • your first example getPoduto should have a better context of name maybe (I’m imagining you’re using the "Product" model) ... say by Pro and then use a Scope in your model:
public function peloPrecoScope($query, $preco = 100) {
   return $query->where('preco', 100);
}

This way you’d wear it like this:

$produto = Produto->peloPreco(200)->first(); // ou get - aqui estou pegando o primeiro registro apenas do retorno

And yes, the check would probably be as you specified.

See nothing prevents you to use as described, often I have situations where I need the return to be "hard" (hard coded) with a get method, but often implement the filter option in the model using Scopes is the output that delivers more reuse of code and better reading comprehension of it.

To better understand the Copes see in the documentation: Eloquent - Query Scopes

  • Wow, that was really helpful. Thank you. I came to this question, because I’m developing a small system in the company where I work, nothing complex, but even without being an advanced programmer, I knew that putting the database interactions in the controllers would give me a headache if I needed to change something in the table for example. So I thought of creating methods( as much energy as possible) within the model.

  • I am glad that I have directed a solution, I would appreciate it if you would mark the answer as you accept

Browser other questions tagged

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