4

I'm trying to find out if my table is empty but I get this error

Call to undefined function App\Http\Controllers\isEmpty()

I did check the question that had a similar title to mine but that didn't have what I needed.

Here is my code

$orders = Order::all();

if(isEmpty($orders))
{
    echo "Im empty";
    die();
 }else{
    echo "im not empty";
     die();
 }
Nikki
  • 195
  • 2
  • 3
  • 13

6 Answers6

8

You should use Model::exists(). It returns true/false and runs a select count(*) from table where query under the hood.

if (Order::exists()) {
    echo "im not empty";
    die();
} else {
    echo "Im empty";
    die();
}
Cameron Wilby
  • 2,222
  • 1
  • 25
  • 35
4

Ok since all of the answers in here are not good/optimized here is the fastest way to check whether a table has any rows/table is not empty

$order = Order::first();
if(is_null($order)) {
    // Table is empty.
}else {
    // Table is not empty.
}

Order::all() and Order::count() is bad because your table may have millions of records in it and when you get all rows you may get memory exception or even system hanging

AH.Pooladvand
  • 1,944
  • 2
  • 12
  • 26
3

You can call eloquent count function to get count and then check if count is equal to zero.

$products = Order::count(); //returns products count
if($products == 0){
    //products table is empty
}

or

if($collection->isEmpty()){
//products table is empty.
}
Afraz Ahmad
  • 5,193
  • 28
  • 38
1

The optimal and fastest way to check if a table is empty is by:

//When using eloquent
if(empty(Order::count())){
   // Do something here
}

Or

//When using query builder
if(empty(DB::table('orders')->count())){
   // Do something here
}

Internally these will count total number of rows on the database itself and it will generate the following query.

select count(*) as aggregate from `orders`
Hemerson Varela
  • 24,034
  • 16
  • 68
  • 69
-1

If you want to check an array, use empty($orders), for a Laravel Collection you can use $orders->isEmpty()

Currently you're calling a function isEmpty(), which doesn't exist.

Try this:

$orders = Order::all();

if($orders->isEmpty())
{
    echo "Im empty";
    die();
 }else{
    echo "im not empty";
     die();
 }
  • This might give issues when you have like a lot of records in that table without a limiter, paging or anything. I would not recommend using this method. Say you have 2000 records. That's 2000 records that get loaded into ram, then hydrated into models, filling up your ram, snooping at CPU capacity. An `::exists()` or `count()` would be more at place, than this overly heavy operation. – Tschallacka Aug 24 '21 at 08:30
-1

According to Laravel Documentation states you can use this way:

$orders = Order::all();
if($orders->isEmpty())
{   
  echo "Im empty";
} else {
  echo "Im not empty";
}
Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64