PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 16, 2022

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

 May 16, 2022     laravel, php     No comments   

Issue

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?


Solution

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  \Illuminate\Http\Request  $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);
    }
}


Answered By - TsaiKoga
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing