Hello Laravel Friends,

In today’s Laravel tutorial, I will explain How to Create GraphQL API in Laravel 8.

GraphQL is a query language for APIs (Application Programming Interfaces) that allows clients to request specific data and shape the response according to their needs.

Let’s find out the steps on How you can create GraphQL API in Laravel 8.

Steps to Create GraphQL API 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 above command will create a Laravel project in a new directory named lara-bookstore in your local development folder or wherever you run the command from.

Now, go to the project folder and run the Laravel project to interact with the default functionality using the following command:

The new Laravel project gets created as follows

Step 2: Install GraphQL Laravel library

Use below command to Install library

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

Output:

Copy of configuration file

Step 3: Create Product Table

Create product table using the migration command

Then add the code as below

Then after run the following command:

Step 4: Create Product Model

The below command is used to create a product model

After that, 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 you need to create type to use GraphQL API. Use the following command to create type

Add the below-mentioned code

Create query

Now you need to create query to use GraphQL API. Use the following command to create query

Add the below-mentioned code

Now you need to add both files to config/graphql.php and than after clear config cache.

config/graphql.php

Output:

The GraphQL API is successfully created for your Laravel 8 project.

GraphQL API

Conclusion:

Hopefully, you have successfully created GraphQL API in Laravel. Alternatively, you can also create REST API in Laravel.

Share the tutorial with your friends to help them create GraphQL API in Laravel and stay updated with us.

Happy Coding!

Click to rate this post!
[Total: 3 Average: 3.7]