0

I have the following problem. When doing a graphql query, i want to return a eloquent relationship with a where condition. As i'm also using this relationship in other parts of my api, i can't write a where condition directly in the relationship function of my model. Also, i can't work with complex where conditions as i don't want to do the where condition in the query itself. The filtered result should come directly from the api.

This is my query type:

type Query {
    pageTree(id: ID): [Page!]!

This is my php query

class PageTree
{
    public function __invoke($_, array $args){
        $user = Auth::user();
        return $args['id'] ? $user->pages->where('parent_id', $args['id'])->all() : $user->pages->whereNull('parent_id')->all();
    }
}

This is my Page type

type Page {
    id: ID!
    name: String!
    slug: String!
    active: Boolean
    subpages: [Page!]
    created_at: DateTime!
    updated_at: DateTime!
}

Subpages should return a hasmany relationship but with a where condition

This is my relationship inside Page Model

public function subpages(){
    return $this->hasMany('App\Models\Page', 'parent_id');
}

It would be easy to do the where condition directly inside this function with e.g. $this->hasMany('App\Models\Page', 'parent_id')->whereNull('deleted_at'); But as i wrote above, i can't do that as i'm using this function in some other parts of my app where i don't need this where condition and if i understood laravel right, you should not do a where conditions direclty inside a eloquent relationship.

Wo can i do that with nuwave/lighthouse?

Thanks, Johannes

joh3rd
  • 5
  • 2
  • 1
    You can add a where condition in the relationship to check if deleted is NULL, but a scope would be a better option. Where conditions with `$this` would not be a good idea. – Gert B. Sep 07 '21 at 07:43
  • Yes, as i wrote, a where condition directly in the relationship is not an option in my case. Is there a way to do this directly in the graphql type anyhow? – joh3rd Sep 07 '21 at 09:48
  • anyone please :) – joh3rd Sep 21 '21 at 12:31

0 Answers0