Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mohammadrasoulasghari's avatar

Equivalent of Eloquent’s firstOrCreate in Query Builder

Hello and good day,

Just as we have a firstOrCreate function in Eloquent, is there anything similar in Query Builder?

Note: I'm specifically asking about firstOrCreate, not updateOrCreate."

0 likes
2 replies
tykus's avatar

No.

firstOrCreate is a convenience method in Eloquent that wraps one or two queries; a read to determine if there is an existing record, and a write if it does not exist.

The Query Builder is "closer to the metal" giving us developers the tools to perform those queries ourselves.

1 like
Sinnbeck's avatar

You can add it as a macro yourself. Something like this should work (untested)

Be sure to use the query Builder class (not eloquent Builder)

Builder::macro('firstOrCreate', function($attributes, $values) {
        if (! is_null($instance = (clone $this)->where($attributes)->first())) {
            return $instance;
        }

        return $this->create(array_merge($attributes, $values));
}

This isn't as strict as eloquent's but should work fine

1 like

Please or to participate in this conversation.