Skip to content

Series Better Laravel · Part 2 of 4

All series →
Redundant Reusable CRUD Backend Laravel

Laravel findOrNew(): Use One Blade Form for Create and Edit

Raheel Shan

Raheel Shan

April 12th, 2025 · 8 min read

Laravel findOrNew(): Use One Blade Form for Create and Edit

Laravel findOrNew() looks up a model by its primary key and, if no row is found, gives you a new unsaved model instead of null or an exception. That one behaviour lets a single Blade form and a single controller action handle both "create" and "edit". Unlike firstOrCreate() and updateOrCreate(), findOrNew() never writes to the database; it only returns a model, and you decide when to save it. This is part 2 of the series, so if you have not seen the lean controller and FormRequest setup, start with part 1.

Quick answer

  1. Call Post::findOrNew($id) to get an existing post, or a blank Post when $id is null or missing.
  2. Use one form.blade.php and fill every input with old('field', $post->field).
  3. On save, call Post::findOrNew($id) again, fill() it with the validated data and save().

What Laravel findOrNew does

findOrNew($id, $columns = ['*']) runs a normal primary key lookup. If a row exists you get that model. If not, you get new Post, with no attributes set and nothing saved. You can check which one you received with $post->exists: it is true for a loaded row and false for a fresh instance. After save() on a fresh instance, $post->wasRecentlyCreated is true.

$post = Post::findOrNew(5);     // post 5 if it exists, otherwise a blank Post
$post = Post::findOrNew(null);  // always a blank Post

$post->exists;                  // true or false

findOrNew vs firstOrNew vs firstOrCreate vs updateOrCreate

These four are easy to mix up. The difference is how you look the row up, and whether anything is saved.

  • findOrNew($id): looks up by primary key. Not found: returns a new model, not saved.
  • firstOrNew($attributes, $values): looks up by any column values. Not found: returns a new model filled with both arrays, not saved.
  • firstOrCreate($attributes, $values): looks up by any column values. Not found: creates and saves the row. Found: returns it unchanged.
  • updateOrCreate($attributes, $values): looks up by any column values. Found: updates it with $values and saves. Not found: creates and saves.

Use findOrNew() when you have an id (or none) and want a model to put in a form. Use the others when you are matching on something like an email address.

Step 1: One route and one controller action

Make the id optional, so /posts/form is the create page and /posts/form/5 is the edit page.

Route::prefix('posts')->name('posts.')->group(function () {
    Route::get('/', [PostController::class, 'index'])->name('index');
    Route::get('/form/{id?}', [PostController::class, 'form'])->name('form');
    Route::post('/form/{id?}', [PostController::class, 'saveForm'])->name('save');
    Route::delete('/{id}', [PostController::class, 'destroy'])->name('destroy');
});
class PostController extends Controller
{
    public function form(GetPostRequest $request, ?int $id = null)
    {
        return view('post.form', ['post' => $request->handle($id)]);
    }

    public function saveForm(SavePostRequest $request, ?int $id = null)
    {
        $post = $request->handle($id);

        session()->flash('message', $post->wasRecentlyCreated
            ? 'Post has been created successfully.'
            : 'Post has been updated successfully.');

        return redirect()->route('posts.index');
    }
}

The ?int $id = null default matters. Without it, a request to /posts/form has no id argument and PHP throws an error.

Step 2: Fetch the model with findOrNew

class GetPostRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [];
    }

    public function handle(?int $id = null): Post
    {
        return Post::findOrNew($id);
    }
}

Step 3: One Blade form for create and edit

The form always receives a $post, either loaded or blank. The second argument of old() is the fallback. It is the saved value when editing, null for a blank model, and the user's own input when validation fails.

<form action="{{ $post->exists ? route('posts.save', $post->id) : route('posts.save') }}" method="post">
    @csrf
    <div>
        <label for="title">Title</label>
        <input type="text" id="title" name="title" value="{{ old('title', $post->title) }}">
        @error('title')
            <div class="text-red-500 text-sm">{{ $message }}</div>
        @enderror
    </div>
    <div>
        <label for="content">Content</label>
        <textarea id="content" name="content" rows="10" cols="80">{{ old('content', $post->content) }}</textarea>
        @error('content')
            <div class="text-red-500 text-sm">{{ $message }}</div>
        @enderror
    </div>
    <button type="submit">Save</button>
</form>

Create links point to route('posts.form'), and edit links point to route('posts.form', $post->id). There is no create.blade.php any more. Your views shrink to index, form and an optional show.

Step 4: Save with findOrNew too

Use the same call in the save request. The validated data fills either the loaded post or the blank one, and save() runs an update or an insert as needed.

class SavePostRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'title' => 'required|string|max:255',
            'content' => 'required|string',
        ];
    }

    public function handle(?int $id = null): Post
    {
        $post = Post::findOrNew($id);
        $post->fill($this->validated())->save();

        return $post;
    }
}

fill() respects mass assignment, so the Post model needs protected $fillable = ['title', 'content'];.

When not to use findOrNew for forms

  • An unknown id opens the create form. /posts/form/99999 does not 404. It shows a blank form, and saving it creates a post with the next free id, not 99999. If you want a 404 for a bad id, use findOrFail() on the edit route.
  • Different rules for create and edit. If the two cases validate differently (a unique email, a password only on create), you will end up branching inside the request. A small $this->route('id') check in rules() is fine; many branches are a sign to split.
  • Authorization. On edit, check that the user may change that post. Put the check in authorize() or a policy, because the same action also creates posts.

If your save logic grows past this, move it out of the FormRequest. See the AQC introduction and the AQC CRUD implementation guide.

FAQ

What does findOrNew do in Laravel? It finds a model by primary key and returns a new, unsaved instance of the model if no row exists.

Does findOrNew save to the database? No. It only returns a model. You save it yourself with save(), which is why it suits forms.

What is the difference between findOrNew and firstOrNew? findOrNew() searches by primary key only. firstOrNew() searches by any attributes you give it and fills the new model with them when nothing matches.

How do I use one form for create and edit in Laravel? Fetch the model with findOrNew($id), fill inputs with old('field', $model->field), and save with findOrNew($id) plus fill() and save().

Can I pass null to findOrNew? Yes. A null id never matches a row, so you get a blank model. That is how the create form loads.

Found this useful?

Support the work that goes into these posts.

Support
Comments


Comment created and will be displayed once approved.
Built with Brandidos