laravel/framework — pull request #3875 by yajra (2014-03-13 03:46:50+00:00)
Title: [Proposal] add findOrNew eloquent method

***Use Case:***
When using one form for both edit and new record. I usually load a record via primary key. Hence, I usually load my model like below and pass it to view to fill-up the fields via ```Form::model()```:

```php
public function getForm($id=0)
{
$user = User::find($id);
if (!$user)
$user = new User;

$this->layout->content = View::make('users.form', compact('user'));
}
```

Using ```findOrNew``` method, we can simplify the code above and ensures that we have a real object passed to view to prevent error referencing to non-object when we used some model methods inside the view:
```php
public function getForm($id=0)
{
$user = User::findOrNew($id);
$this->layout->content = View::make('users.form', compact('user'));
}
```

It can also be used on saving a record. If a record was found, it will update the record. If not, then it will create a new record (assuming all validations passed). Making it simple to update/insert a record.
```php
public function postForm($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!');
}
```

I am also aware that we can use ```firstOrNew``` for this but the difference is using ```findOrNew``` will find the record via primary key while ```firstOrNew``` uses the attributes.

Counter part ``firstOrNew`` implementation. But then again, you have to specify an array with primary key on it.
```php
public function getForm($id=0)
{
$user = User::firstOrNew(array('id'=>$id));
$this->layout->content = View::make('users.form', compact('user'));
}
```