Search code examples
graphqllaravel-lighthouse

How to shuffle results in Lighthouse GraphQL (order by random)?


I see docs for @orderBy but am curious how I could sort my Lighthouse GraphQL results randomly, kind of like inRandomOrder in Laravel:

$randomUser = DB::table('users')
            ->inRandomOrder()
            ->first();

Or like RAND() in MySQL:

SELECT col1, col2
FROM mytable
ORDER BY RAND();

Solution

  • Currently it is not possible out of the box with lighthouse since there is no RAND SortOrder Enum.

    You could use a scope for that.

    Suppose you want to grab randomly some users from your table. Create a scope in you user query in your schema.graphql

    type Query {
        posts(
            random: Boolean @scope(name: "random")
        ): [User!]!
    }
    

    Create the scope in your App\User.php:

    
    // ...
    
    /**
     * Shuffles the users randomly
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
     public function scopeRandom($query) {
        return $query->inRandomOrder();
     }
    
    // ...
    
    

    Utilize the scope in your query:

    {
      users(random: true) 
      {
        id,
        email,
        username
      }
    }
    

    This is fine for small datasets but keep in mind that for larger datasets this could be a possible performance bottleneck.