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

mistre83's avatar

Find or fail - Strange behaviour

Hi to all, in my controller i have a find or fail with the input value:

$order = Order::findOrFail($order_id)

If $order_id do not exists, the function throw an exception, and is ok.

But, if i pass the following value (with an existing order):

  • 1234
  • 1234abc

in both case, the order is found (and the order is 1234)

If i pass a totally inexistent order (for example 345432, that do not exist), this this case the exception is raised

0 likes
5 replies
tisuchi's avatar

I simply suggest you use firstOrFail() instead of findOrFail().

$order = Order::where('order_id', $order_id)->firstOrFail();

Hope it will work fine.

1 like
jenky's avatar

I don't see anything strange here. If the record couldn't be found in the database, the exception is raised with findOrFail, same for firstOrFail.

jenky's avatar

@tisuchi yeah, i know the difference, but from his code.

$order = Order::findOrFail($order_id);

I think the $order_id is the value of the id field in the table.

gmosalazar's avatar

findOrFail() won't check for 'the field named id' in a table, it'll look for the passed value within the specified primary column of a table, whether that's 'id' (by default) or 'thisIsMyPrimaryKey'.

I wouldn't recommend using firstOrFail() it seems like that's addressing the consequence and not the issue.

if for any reason the primary key on the table isn't 'id', you should set it up in the Model and that should make findOrFail() work as expected.

Please or to participate in this conversation.