Laravel create or update without two queries

后端 未结 6 2246
有刺的猬
有刺的猬 2020-12-15 09:21

I\'m trying to use one form for both creates and updates. Both actions save through this method:

public function store() {
    $data = Input::all();
    $dat         


        
6条回答
  •  不思量自难忘°
    2020-12-15 10:03

    You may try this:

    $data = Input::except('_token');
    $newOrUpdate = Input::has('id') ? true : false;
    $isSaved = with(new Feature)->newInstance($data, $newOrUpdate)->save();
    

    If $data contains an id/primary key it'll be updated otherwise insert will be performed. In other words, for updating, you need to pass the id/primary key in the $data/attributes with other attributes and second argument in the newInstance method must be true.

    If you pass false/default to newInstance method then it'll perform an insert but $data can't contain an id/primary key. You got the idea and these three lines of code should work. $isSaved will be a Boolean value, true/false.

    You may write the code using one line:

    with(new Feature)->newInstance($data, array_key_exists('id', $data))->save();
    

    If $data contains id/primary key then it'll be updated, otherwise an insert will be performed.

提交回复
热议问题