Site icon MageComp Blog

How to Create GraphQL API in Laravel 8?

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:

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!

Exit mobile version