Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 INSERT if Input::get('id') is set, or an UPDATE if it's not.

like image 451
mpen Avatar asked Apr 26 '14 20:04

mpen


People also ask

How do you use create or update in Laravel?

Syntax. $flight = Model::updateOrCreate( ['field1' => 'value'], [field=>value, field1=>value] ); The first value in the array is used to search in the table if it exists, and if not it will insert the value or it will update for the match of the first parameters in the array. Let us try an example using it.

How does updateOrCreate work in Laravel?

The updateOrCreate method attempts to find a Model matching the constraints passed as the first parameter. If a matching Model is found, it will update the match with the attributes passed as the second parameter.

How do I use whereBetween in Laravel?

The whereBetween() method is a query builder chained alongside other Laravel query builders used to fetch data from the database. The whereBetween() method queries the database table to fetch rows of records from the database within a range of values.

What is difference between create and insert in Laravel?

create() is a function from Eloquent, insert() - Query Builder. In other words, create is just an Eloquent model function that handles the creation of the object to the DB (in a more abstract way). Insert however tries to create the actual query string.


4 Answers

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.

like image 147
Keith Holliday Avatar answered Nov 08 '22 20:11

Keith Holliday


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.

like image 41
Vladislav Rastrusny Avatar answered Nov 08 '22 21:11

Vladislav Rastrusny


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.

like image 31
yajra Avatar answered Nov 08 '22 21:11

yajra


Find or New based on primary key id

$data = Input::all();
$user = User::findOrNew($id);  // if exist then update else insert
$user->name= $data['user_name'];
$user->save();

First or New based on non-primary key single filed

$user = User::firstOrNew(['field' => $data['value'] ]);
$user->name= $data['user_name'];
$user->save();

First or New based on non-primary key multiple filed

$user = User::firstOrNew([
                     'field1'=>$data['value1'],
                     'field2'=>$data['value2']
                     ]);
$user->name= $data['user_name'];
$user->save();
like image 32
Majbah Habib Avatar answered Nov 08 '22 20:11

Majbah Habib