mpen mpen - 2 months ago 30x
PHP Question

Laravel create or update without two queries

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

public function store() {
$data = Input::all();
$data['company_id'] = Auth::user()->company_id;
$validator = Validator::make($data, Feature::$rules);

if($validator->fails()) {
return Redirect::back()->withErrors($validator)->withInput();

Feature::firstOrNew(['id' => Input::get('id')])->update($data);

return Redirect::route('features.index');

How can I rewrite this line:

Feature::firstOrNew(['id' => Input::get('id')])->update($data);

So that it doesn't fetch the object from the database first? There's no need for that; I'm not doing anything with it. It should either issue a
is set, or an
if it's not.


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');

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

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

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