Laravel create or update without two queries
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.