Home  >  Q&A  >  body text

PHP OOP - Return result of $obj->get() and $obj->get()->count() without calling another method

It's hard to explain exactly what I want, but I have to try...

Laravel Eloquent inspired me to write a simple php class to use the database.

As far as we know we can do this in Laravel:

$run = DB::table('users')->where('id', 3)->where('level', 2)->get();

We do this too:

$run = DB::table('users')->where('id', 3)->where('level', 2)->get()->count();

We can also do this:

$run = DB::table('users')->where('id', 3)->where('level', 2)->get()->first();

We can do it too:

$run = DB::table('users')->where('id', 3)->where('level', 2)->get()->pluck('id')->toArray();

I've never tried it, but I believe it works too:

$run = DB::table('users')->where('id', 3)->where('level', 2)->get()->pluck('id')->toArray()->first();

The question is "How does it work?"

How should I write this to return appropriate results in any way?

// It was easy to write my code to return total results if I write like that
$run = DB::from('users')->where('id', 3)->where('level', 2)->get()->count();

// Or to return first result if I write like that
$run = DB::from('users')->where('id', 3)->where('level', 2)->get()->first();

// But what sould I do to return all the results if write like that (As eloquent works).
$run = DB::from('users')->where('id', 3)->where('level', 2)->get();

I need something like "if - else case for method", for example:

function __construct() {
   if(if aint`t no calling any methods except **get()** ){
      // Lets return default method
      return $this->results();
   }
   else{
      // Do whatever...
   }
}

This is my complete code:

https://github.com/amirandev/PHP-OOP-DB-CLASS/blob/main/db.php

P粉742550377P粉742550377182 days ago419

reply all(1)I'll reply

  • P粉536532781

    P粉5365327812024-04-02 09:51:57

    As far as I know, when you try something like that

    $run = DB::from('users')->get()->count();

    You get all users and php/laravel count users which means

    $users = DB::from('users')->get(); // get all users
    $usersConut = $users->count();  //count them away of database/mysql

    Same as first()

    When you use this code DB::from('users')->count(); you are actually asking MySql for the counts instead of doing them on the backend count.

    I highly recommend using this package barryvdh/laravel-debugbar to help you view the database quarris.

    reply
    0
  • Cancelreply