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

DevinSephone's avatar

firstOrCreate/New with MySQL operators

I am trying to use the firstOrCreate or firstOrNew Eloquent methods to find a record in the database by a column in a given table. I'd like to use the like MySQL operator to search for records that do not 100% match the current entry. From what I can tell, these methods only allow for the column and the value with no special operators. Is there a way to use these methods how I have described?

Here is an example of what I would like to do (does not work currently)

$dma = Dma::firstOrCreate(
    ['name', 'like', "%$market%"]
);

The above code produces the following error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from column where (0 = name and 1 = like and 2 = %Market%) limit 1)

I understand that this error occurs because the array is not formed properly for the firstOrCreate method, but is there a way to make this work or an alternative that will accomplish what I am looking to do?

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

I believe you cannot do it like this; if you think about it, what would the name be if it did work?

You would need to:

$dma = Dma::where('name', 'like', "%$market%")->first();

if (!dma) {
    $dma = DMA::create(['name' => $market]);
}

return $dma;
1 like
DevinSephone's avatar

Thank you @Dry7 & @tykus, this is what I anticipated, I just wanted to check and make sure I was not overlooking something that would accomplish what I wanted to do.

@tykus The code you provided works. Only adjustment is that the if statement check is missing a $ before dma.

1 like

Please or to participate in this conversation.