Laravel 9 GraphQL API CRUD Tutorial Example
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data.
GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
Installment
Once you have created a new Laravel application, you need to install nuwave/lighthouse using Composer:
composer require nuwave/lighthouse
Publish the default schema
Lighthouse includes a default schema to get you going right away. Publish it using the following artisan
command:
php artisan vendor:publish --tag=lighthouse-schema
Install GraphQL DevTools
To make use of the amazing tooling around GraphQL, we recommend installing GraphiQL .
composer require mll-lab/laravel-graphiql
After installation, visit /graphiql
to try it.
Configuration
Lighthouse comes with sensible configuration defaults and works right out of the box. Should you feel the need to change your configuration, you need to publish the configuration file first.
php artisan vendor:publish --tag=lighthouse-config
The configuration file will be placed in config/lighthouse.php
.
Schema
A schema defines the capabilities of a GraphQL server. Much like a database schema, it describes the structure and the types your API can return.
Types
Types are the primary building blocks of a GraphQL schema. They define the capabilities of your API and the kind of data you can get from it.
Query
Every GraphQL schema must have a Query
type which contains the queries your API offers. Think of queries as REST resources which can take arguments and return a fixed result
Mutation
In contrast to the Query
type, the fields of the Mutation
type are allowed to change data on the server.
Open your graphql/schema.graphql
and add the following :
type Query{
"collection of user"
users: [User!]! @paginate
"user find by id"
user(id: ID @eq ): User @find
}
type Mutation {
"insert user ,validation rule in email and password"
createUser(name:String!,email:String! @rules(apply: ["email", "unique:users"]) ,password:String! @rules(apply: ["min:8"])): User @create
"update user"
updateUser(id: ID!, name: String): User @update
"delete user"
deleteUser(id: ID!): User @delete
"insert or update the data in upsert"
upsertUser(id:ID!,name:String,email:String,password:String): User! @upsert
}
type User{
id: ID,
name: String,
email: String,
}