Laravel running multiple operations with a single DB instance

It sometimes occur that you have a lot of queries to run a single function. Let’s say you have a loop in which you keep querying the database. Although it’s recommended to optimize your code, if you are more efficient (not lazy) like me, you could run all queries in a single DB Instance.

public function doLotsOfStruff()
{
    DB::transaction(function () {
        $users = DB::table('users')->get();
        $bills = DB::table('bills')->lists('id');
    });
}

The code above will run a single instance of DB instead of 2. You could also run the same like this

public function doLotsOfStruff()
{
   DB::beginTransaction();

   $users = DB::table('users')->get();
   $bills = DB::table('bills')->lists('id');

   DB::commit();
}

The second method is the more flexible one as midway you may decide to cancel everything and literally rollback

public function doLotsOfStruff()
{
   DB::beginTransaction();

   $users = DB::table('users')->get();

   // if we don't have users, we stop everything
   if ( !$users ) DB::rollBack(); 

   $bills = DB::table('bills')->lists('id');

   DB::commit();
}

Did I say Madrid lost 2-3 in today’s El Classico? Bummer! Hala Madrid!