Skip to content
Advertisement

How to use a resource collection toArray and DB (without Eloquent)

I have this query (in a repository, without using Eloquent):

    public function getUsersOfASchool($schoolId, $request)
    {

        $query = DB::table('school_users as su')
            ->join('users as u', 'u.id', 'su.user_id')
            ->where('su.school_id', $schoolId);

        $users = $query->paginate();

        return $users;
    }

I have this controller:

try{
        $users = $this->userRepository->getUsersOfASchool($school->id, $request->all());
    } catch(Exception $e) {
        return response()->json(['message'=>'Bad request '.$e->getMessage()], 400);
    }

    return new UserCollection($users);

And at least, I have this collection:

public function toArray($request)
{
    return parent::toArray($request);
}

I have this error 500:

“message”: “Call to undefined method stdClass::toArray()”,

I think it is because I use the ‘DB’ facade instead of Eloquent. So how to work with ‘DB’ facade and collection?

Advertisement

Answer

Yes, because query builder return a collection with stdClass inside.

And ResourceCollection‘s method toArray will map the collection, then run the toarray() on stdClass. So error occurs.

However, eloquent builder collection will map the collection, run the toArray() on model’s object. And this object has toArray() method.

Here is the source code:

    /**
     * Transform the resource into a JSON array.
     *
     * @param  IlluminateHttpRequest  $request
     * @return array
     */
    public function toArray($request)
    {
        return $this->collection->map->toArray($request)->all();
    }

So you can rewrite the toArray() method for query builder in your resource:

public function toArray($request)
{
    // return parent::toArray($request);

    $collection = $this->collection;
    if (method_exists($collection->map, 'toArray')) {
        return $collection->map->toArray($request)->all();
    } else {
        // for stdClass
        return json_decode(json_encode($collection, true), true);
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement