firstOrCreate/New with MySQL operators

Published 9 months ago by bcharron

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?

Best Answer (As Selected By bcharron)
tykus

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;
Dry7
Dry7
9 months ago (151,880 XP)

@bcharron No, I think the check should be done manually

tykus
tykus
9 months ago (658,860 XP)

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;
bcharron

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.

Please sign in or create an account to participate in this conversation.