S
S
siRius322021-04-03 18:37:30
Laravel
siRius32, 2021-04-03 18:37:30

Use Builder pattern for model fields in Laravel?

1. It is necessary to create a model with certain fields and perform checks before saving, in which conditions requests for other data, etc., is using the builder pattern in this case a good idea? those. set the fields in the builder->setSomething() methods and in the last builder->save() method do a check before saving or throw an exception if the check fails.
2. Modify an existing model by passing the model id to the constructor
Builder($id = null) {
$this->model = $id ? Model::findOrFail($id) : new Model();
}

Is it done like this at all?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
the5x, 2021-04-03
@the5x

Builder is used when you need multiple conditions for a particular query. For example GET request with several parameters. For example, a product selection from the database by color, size, availability, etc. Check every incoming request. Here is an example of usage:
https://timacdonald.me/dedicated-eloquent-model-qu...

J
jazzus, 2021-04-04
@jazzus

At first, it is better to study the "examples from the documentation" pattern, and then the best practices from the Internet, packages, and other bikes)

$this->model = $id ? Model::findOrFail($id) : new Model();

For what logic this scheme is not clear. It looks like firstOrCreate and then Laravel has a method of the same name. If this is a type of show method, then you need to use Model Binding
And there you do not need to check any id and findOrFail is included. Examples of good routes/methods/names are in resource controllers/routes. I advise you to look.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question