L
L
Lucius Mooning2018-04-20 12:53:51
Laravel
Lucius Mooning, 2018-04-20 12:53:51

How to make a unified method for store and update models?

Good afternoon!
How to competently unify the function for the store and update methods of the model, if the form data is stored in almost the same uniform code?
Differences: in function store new is used, and in update - element with index id is initially searched through findorFail
What is the best practice in your opinion?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Dergachov, 2018-04-20
@honeymoonny

public function storeOrUpdate($id = null,  array $fields){
   $model = $id !== null ? Model::findOrFail($id) : new Model();
}

S
Sergey Gerasimov, 2018-04-20
@mrTeo

In the store method we specify:

$model = new Model();
$this->update($request, $model);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question