Laravel

How to Create GraphQL API in Laravel 8?

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:

composer create-project laravel/laravel:^8.0 graphql-app

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:

//move into project

cd graphql-app

//Run the project

php artisan serve

The new Laravel project gets created as follows

Step 2: Install GraphQL Laravel library

Use below command to Install library

$ composer require rebing/graphql-laravel

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

$ php artisan vendor:publish –provider="Rebing\GraphQL\GraphQLServiceProvider"

Output:

Step 3: Create Product Table

Create product table using the migration command

 php artisan make:migration create_products_table

Then add the code as below

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id('product_id');
            $table->string('product_name');
            $table->string('product_description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Then after run the following command:

$ php artisan migrate

Step 4: Create Product Model

The below command is used to create a product model

$ php artisan make:model Product

After that, add the following code

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'product_id',
        'product_name',
        'product_description',
    ];
}

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

$ php artisan make:graphql:type GetProduct

Add the below-mentioned code

create query :
declare(strict_types=1);

namespace App\GraphQL\Types;

use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Type as GraphQLType;

class GetProduct extends GraphQLType
{
    protected $attributes = [
        'name' => 'GetProduct',
        'description' => 'A type'
    ];

    public function fields(): array
    {
        return [
            "product_id" => [
                "type" => Type::int(),
                "description" => 'produt_id of product',
            ],
            "product_name" => [
                "type" => Type::string(),
                "description" => 'product_name of produc',
            ],
            "product_description" => [
                "type" => Type::string(),
                "description" => 'product_description of produc',
            ],
        ];
    }
}

Create query

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

$ php artisan make:graphql:query GetProduct

Add the below-mentioned code

declare(strict_types=1);

namespace App\GraphQL\Queries;

use App\Models\Product;
use Closure;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Facades\GraphQL;
use Rebing\GraphQL\Support\Query;
use Rebing\GraphQL\Support\SelectFields;

class GetProduct extends Query
{
    protected $attributes = [
        'name' => 'getProduct',
        'description' => 'A query'
    ];

    public function type(): Type
    {
        return Type::listOf(GraphQL::type("GetProduct"));
    }

    public function args(): array
    {
        return [

        ];
    }

    public function resolve($root, array $args, $context, ResolveInfo $resolveInfo, Closure $getSelectFields)
    {
        /** @var SelectFields $fields */        $fields = $getSelectFields();
        $select = $fields->getSelect();
        $with = $fields->getRelations();

        $data = Product::all();

        return $data;
    }
}

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

config/graphql.php

'schemas' => [
        'default' => [
            'query' => [
                "getProduct" => \App\GraphQL\Queries\GetProduct::class,
            ],
            'mutation' => [
                // ExampleMutation::class,
            ],
            // The types only available in this schema
            'types' => [
                "GetProduct" =>  \App\GraphQL\Types\GetProduct::class,
            ],

            // Laravel HTTP middleware
            'middleware' => null,

            // Which HTTP methods to support; must be given in UPPERCASE!
            'method' => ['GET', 'POST'],

            // An array of middlewares, overrides the global ones
            'execution_middleware' => null,
        ],
    ],

Output:

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

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: 2 Average: 5]
Bharat Desai

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer 🏅 with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess ♟️ or Cricket 🏏.

Recent Posts

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

14 hours ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

3 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

3 days ago

Magento 2: How to Add Header and Footer in Checkout

Hello Magento Friends, In today’s blog, we will discuss adding a header and footer to…

4 days ago

Understanding Flexbox Layout in React Native

Hello React Native Friends, Building a visually appealing and responsive mobile app is crucial in…

6 days ago

HYVÄ Themes Releases: 1.3.6 & 1.3.7 – What’s New

We have brought exciting news for Magento store owners. Hyvä Themes recently released 1.3.6 and…

6 days ago