I'm trying to update multiple models with a directive, but the current @update directive does not support multiple ids. I would basically want the @delete directive (where you can use a list of ids). To update multiple models. I'm guessing I could create a custom directive, but it's alot of code there that I can't wrap my head around. I've tried to read the docs to understand how to create a custom directive, but I can't get it to work.
So the DeleteDirective.php got this:
/**
* Bring a model in or out of existence.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
protected function modifyExistence(Model $model): void
{
$model->delete();
}
And I would basically want this (for multiple ids):
/**
* Update a model to read true
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
protected function updateRead(Model $model): void
{
$model->update(['read' => true]);
}
By defining a mutation query like this:
type Mutation {
updatePostsToRead(id: [ID!]!): [Post!]! @updateRead
}
And doing a query like this:
{
mutation {
updatePostsToRead(id: [6,8]) {
id
amount
}
}
}
Does anyone know how I would go by doing this? Or can point me in the right direction?
Found a way to do it without creating a custom directive. Just made a custom mutation with php artisan lighthouse:mutation updatePostsToRead
.
updatePostsToRead.php:
class updatePostsToRead
{
/**
* Return a value for the field.
*
* @param null $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
* @param mixed[] $args The arguments that were passed into the field.
* @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context Arbitrary data that is shared between all fields of a single query.
* @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
* @return mixed
*/
public function __invoke(
$rootValue,
array $args,
GraphQLContext $context,
ResolveInfo $resolveInfo
) {
// TODO implement the resolver
\DB::table('posts')
->whereIn('id', $args["ids"])
->update(['read' => true]);
$posts = Post::whereIn('id', $args["ids"])->get();
return $posts;
}
}
Schema:
type Mutation {
updatePostsToRead(ids: [ID]): [Post]
}
Query on client:
mutation{
updatePostsToRead(ids: [2,6,8]) {
id
description
read
}
}