Hello Laravel Friends,

In this blog, I will illustrate How to Create GraphQL Mutation in Laravel 8.

In Laravel 8, a GraphQL mutation is a way to define and execute operations that modify data on the server. It allows you to perform create, update, and delete operations on your data through GraphQL.

Let’s find out How to Create GraphQL Mutation in Laravel 8?

Steps to Create GraphQL Mutation in Laravel 8:

Step 1: Create a New Laravel Project

To begin, we will create a new Laravel application using Composer by running the following command from the terminal:

The preceding command will create a Laravel project in a new directory named lara-bookstore in your local development folder or whenever you run the command from. Go to the project folder and run the Laravel project to interact with the default functionality using the following command:

//move into project

//Run the project

Create Laravel Project

Step 2: Install GraphQL Laravel library

// Install library

Once the installation is completed, publish a copy of the configuration file from the vendor folder using this command:

Output:

Install GraphQL Library

Step 3: Create Product Table

Using the below migration command, you can create a product table

Then add the following code

Then run the following command:

Step 4: Create Product Model

Run the below command to create a book model

Then add the following code

Step 5: Building GraphQL Server

Begin by creating a GraphQL folder in the app folder of your application. Within this folder, create three new subfolders, namely:

  • Mutations: This folder will house classes that will be used to carry out the insert, update, and delete operations.
  • Queries: GraphQL queries will be used to fetch data from the database and the classes for that functionality will be defined here.
  • Types: Types are objects that represent the kind of objects that can be retrieved from the database. The BookType class will be housed here.

Create Type:

Now we will create type to use for the GraphQL API. Use the following command to create type,

Then add the code below

Create Mutation:

Now we will create mutation to use for the GraphQL API. Use the following command to create mutation,

After that, add the below code

Now you need to add both files to config/graphql.php and then clear the config cache.

config/graphql.php

Now open Postman and try the below,

Output :

Conclusion:

That’s it! You have now created a GraphQL mutation in Laravel 8 to handle data modifications in a structured and efficient manner. You can add more mutations following a similar pattern and extend your GraphQL API as needed.

Also learn How to Create GraphQL API in Laravel 8.

Happy Coding!

Click to rate this post!
[Total: 1 Average: 5]