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

mojtabaavahdati's avatar

contains vs exists

As the title says my question is about the difference between Laravel exists and contains methods. I wonder why they are not named the same? I know one of them is operating on collections(contains) and the other one is a method in query builders but as far as I understand now (& I might be wrong) their functionality is quite the same and maybe naming them equally could make them easier to be remembered(naming consistency?).

contains => check to see if there's at least one item(in the collection) with the conditions specified.

exists => check to see if there's at least one record(in the database table) with the conditions specified.

Finally I want to make it clear that this is neither a criticism nor a suggestion I just want to make sure if my beginner understanding of them is not erroneous. Maybe they are doing different things so my hope is that someone here will correct me in that case.

0 likes
2 replies
NickVahalik's avatar
Level 8

Their functionality is very different. The exists() method returns true/false based on whether or not any values in the DB are returned by the specified query:

if (User::exists()) {  //  only do something if a user exists in the DB

Contains, on the other hand, returns true only if the specific Collection contains a particular item.

   if ($collection->contains('Desk')) { // Do something.

That is, in order to emulate exists() on a collection to see if anything exists at all, you'd end up using $collection->isEmpty() instead.

So while the two can function in roughly the same capacity (you can craft a query which selects a user with a specific ID for instance), contains() will always function with a single element vs. exists() which can test for the presence of any objects meeting a criteria you specify in the SQL query.

1 like

Please or to participate in this conversation.