0
votes

I am using Eloquent in Laravel 3 and would like to know what the best practices are for conditionally updating a record in a database table. I have the key in my model set to the 'email' field and have found that I can do a check using the find() method and if nothing is found I can create a new instance of the model and save the record but this approach looks/feels clunky and cumbersome.

What is the cleanest way to see if a record exists matching a key value that is passed in and based on that create a new record or just update an existing one?

    $form = FormDB::find('[email protected]');

    if($form) {
        $form->text = "Updated";
        $form->save();
    } else {
        $form = new FormDB;
        $form->email = "[email protected]";
        $form->text = "Inserted";
        $form->save();
    }
1

1 Answers

1
votes

You may try this

$form = !FormDB::find('[email protected]') ? new FormDB : FormDB::find('[email protected]');
$form->email = !$form->email ? "[email protected]" : $form->email;
$form->text = !$form->text ? "Inserted" : "Updated";
$form->save();