Broshi
Broshi

Reputation: 3592

Laravel5 Eloquent custom method return array

I have a static method in my User model which counts something, i am using a raw statement:

static function countOrders($userId)
{
   $sql = "SOME CUSTOM-COMPLICATED QUERY";
   $result = \DB::select( \DB::raw( $sql ) );
   return $result; // <-- toArray() ? returns Exception!
}

Somewhere in my controller:

$orders = User::countOrders(*USER-ID*);

How can I get an array with records as arrays and not objects without modifying the global configuration for the FETCH method?

Upvotes: 1

Views: 236

Answers (1)

Fabio Antunes
Fabio Antunes

Reputation: 22862

You don't need to run toArray().

When executing raw queries select returns array, it's stated in the docs:

The select method will always return an array of results.

static function countOrders($userId)
{
   $sql = "SOME CUSTOM-COMPLICATED QUERY";
   $result = \DB::select( \DB::raw( $sql ) );
   return $result;
}

Upvotes: 3

Related Questions