Laravel create or update without two queries Laravel create or update without two queries laravel laravel

Laravel create or update without two queries


This is what I use:

Model::updateOrCreate(   ['primary_key' => 8],   ['field' => 'value', 'another_field' => 'another value']);

The second parameter is an array of the data for the model you want to save.


If you have all fields unguarded in your model, I think you can do it like this:

$feature = new Feature($data);$feature->exists = Input::has('id');$feature->save();

If you have some guarded fields, then you can unguard it first:

$feature = new Feature();$feature->unguard();$feature->fill($data);$feature->exists = Input::has('id');$feature->reguard();$feature->save();

The reguard() call is not actually needed if you don't do anything else with the model.


I used to have this problem and created an accepted pull request on Laravel which you can use. Try the code below. The method you will basically need is the findOrNew.

public function store($id=0){    $user = User::findOrNew($id);    $data = Input::all();    if (!$user->validate($data)) {        return Redirect::back()->withInput()->withErrors($user->errors);    }    $user->fill($data);    $user->save();    return Redirect::to('/')->with('message','Record successfully saved!');}

My model uses self validation but you can create your own validation like the one you have now.