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

hypergalaktisch's avatar

firstOrCreate case sensitive

Hey, is there a possibility to firstOrCreate a model with case sensitive?

0 likes
9 replies
mstrauss's avatar

Hi @hypergalaktisch

That's a good question. Unfortunately, from the actual method below, it doesn't seem to be possible with using the framework's standard firstOrCreate method. In my opinion, this is desired behavior, but I can see where there would be times where case sensitive version would be useful.

 /**
     * Get the first record matching the attributes or create it.
     *
     * @param  array  $attributes
     * @param  array  $values
     * @return \Illuminate\Database\Eloquent\Model|static
     */
    public function firstOrCreate(array $attributes, array $values = [])
    {
        if (! is_null($instance = $this->where($attributes)->first())) {
            return $instance;
        }

        return tap($this->newModelInstance($attributes + $values), function ($instance) {
            $instance->save();
        });
    }
ftiersch's avatar

Do you mean case insensitive? Because the default way should be case sensitive.

mstrauss's avatar

@ftiersch

Because the where clause is translated to an sql clause of something like SELECT * FROMtableWHEREValue= "input", it should be case insensitive as that is typically the default, at least for MySQL.

EDIT And I am just seeing now that I wrote:

but I can see where there would be times where case insensitive version would be useful

I corrected, good catch

ftiersch's avatar
value='input'

should be case sensitive - meaning it is sensitive to casing and "input" is something else than "iNput" because the case is different.

value LIKE 'input'

This would be case insensitive

Nakov's avatar

@ftiersch the default is case insensitive I believe. I just tried on my project to use where and both value and VaLue return the same result.

ftiersch's avatar

Whoops. I just tried and you're right. :) Didn't even know that, I always used LIKE for case insensitivity.

Sorry @mstrauss , totally got that wrong.

1 like
Nakov's avatar

@hypergalaktisch You can first fetch the record using case sensitive, and then based on the result create if nothing found:

$user = User::where(DB::raw('BINARY `name`'), $name)->first();

if ( ! $user )
{
    // user not found so create it.
}
Snapey's avatar

Probably the only way is to add your own static method to your model which uses the 'BINARY' option

SELECT * FROM `table` WHERE `column` = BINARY 'value'
alexei002's avatar

You can add where() before calling firestOrCreate() with empty first argument

User::where('name', 'ilike', $value)->firstOrCreate([], ['name' => $value])

Please or to participate in this conversation.