LaraChat Articles – How To Build GraphQL APIs Using Laravel

Grab your free Laravel Guide today and see how to boost your Laravel Experience Laravel provides a clean interface for building www.iankumu.com/blog/laravel-rest-api/.

* * @return array */ public function definition() { $userIDS = DB::table(‘users’)->pluck(‘id’); return [ ‘title’ => $this->faker->words(2, true), ‘content’ => $this->faker->sentences(3, true), ‘author_id’ => $this->faker->randomElement($userIDS)]; }}

//App/GraphQL/Queries/Articles/ArticlesQuery ‘articles’, ‘description’ => ‘A query to fetch all articles’ ]; public function type(): Type { // return Type::listOf(GraphQL::type(‘Articles’)); //return all results return GraphQL::paginate(‘Articles’); //return paginated results } public function args(): array { return [ ‘limit’ => [ ‘type’ => Type::int()], ‘page’ => [ ‘type’ => Type::int()] ]; } public function resolve($root, array $args, $context, ResolveInfo $resolveInfo, Closure $getSelectFields) { /** @var SelectFields $fields */ $fields = $getSelectFields(); $select = $fields->getSelect(); $with = $fields->getRelations(); if (!array_key_exists(‘limit’, $args) || !array_key_exists(‘page’, $args)) { $articles = Articles::with($with)->select($select) ->paginate(5, [‘*’], ‘page’, 1); } else { $articles = Articles::with($with)->select($select) ->paginate($args[‘limit’], [‘*’], ‘page’, $args[‘page’]); } return $articles; // return Articles::select($select)->with($with)->get(); This returns all records without pagination }}

‘UpdateArticle’, ‘description’ => ‘A mutation for Updating an Article’ ]; public function type(): Type { return GraphQL::type(‘Articles’); } public function args(): array { return [ ‘id’ => [ ‘type’ => Type::nonNull(Type::id()), ‘description’ => ‘The auto incremented Article ID’ ], ‘title’ => [ ‘type’ => Type::nonNull(Type::string()), ‘description’ => ‘A title of the Article’ ], ‘content’ => [ ‘type’ => Type::nonNull(Type::string()), ‘description’ => ‘The Body of the Article’ ], ‘author_id’ => [ ‘type’ => Type::nonNull(Type::id()), ‘description’ => ‘The Author of the Article’ ]]; } public function resolve($root, array $args, $context, ResolveInfo $resolveInfo, Closure $getSelectFields) { $article = Articles::findOrFail($args[‘id’]); $article->update($args); return $article; }}

Read more here: Source link