Laravel with GraphQL — Getting Started for Beginners
Laravel, one of the most popular PHP web application frameworks, has gained much attention in the development world. It provides a comprehensive set of tools for building web applications, including authentication, routing, caching, and database migrations. GraphQL, on the other hand, is a query language for APIs that have become popular in recent years for its flexibility and efficiency.
This article will explore how to get started with Laravel and GraphQL, even if you’re a beginner.
What is GraphQL?
GraphQL is a query language for APIs developed by Facebook in 2012. It provides a flexible syntax for describing data requirements and allows clients to request only the data they need, reducing the amount of data transferred over the network. With GraphQL, clients can specify the exact fields and relationships they need in a single request, instead of relying on multiple RESTful API endpoints. There are 3 main types in GraphQL, Query
Mutation
Subscription
To read more please visit the official documentation graphql.org
Why use GraphQL with Laravel?
Laravel’s built-in RESTful API support is excellent and provides an easy way to create APIs for your applications. However, RESTful APIs can become complex and hard to maintain as your application grows. GraphQL, on the other hand, provides a simpler and more efficient way to handle data requirements.
With GraphQL, you can define a single endpoint that can handle all data requests, rather than having multiple endpoints for different resources. This makes it easier to manage and maintain your APIs, especially if your application has many different data types.
Getting started with Laravel and GraphQL
Before we begin, make sure you have Laravel installed on your machine. You can download it from the official Laravel website or install it using Composer.
Step 1: Install the necessary package
To get started with GraphQL in Laravel, you’ll need to install this package.nuwave/lighthouse
: This package provides a simple way to add GraphQL to your Laravel application.
You can install the package using Composer by running the following command:
composer require nuwave/lighthouse
Step 2: Configure
To publish the configuration file you can run this command
php artisan vendor:publish --tag=lighthouse-config
The configuration file will be placed in config/lighthouse.php
To enable CORS update your config/cors.php
return [
- 'paths' => ['api/*', 'sanctum/csrf-cookie'],
+ 'paths' => ['api/*', 'graphql', 'sanctum/csrf-cookie'],
...
];
Step 3: Create a GraphQL schema
Once you’ve installed the necessary package, you’ll need to create a GraphQL schema for your application, to do so, we can run this command provided by the package
php artisan vendor:publish --tag=lighthouse-schema
This will create a graphql folder under the root folder and a schema.graphql
file inside it. In this file, there is a definition of User
type, which is the same as your Laravel model. You can specify what attributes the client can request.
For example: in the schema.graphql
type User {
"Unique primary key."
id: ID!
"Non-unique name."
name: String!
"Unique email address."
email: String!
"When the email was verified."
email_verified_at: DateTime
"When the account was created."
created_at: DateTime!
"When the account was last updated."
updated_at: DateTime!
}
The schema defines the types of data available in your application and the relationships between them. Next, let's create a query to handle User
retrieval process.
You can create a new file by running the following command in your Laravel application’s root directory:
php artisan lighthouse:query UserQuery
This will create a new file named UserQuery.php
in the app/GraphQL/Queries
directory. You can define your GraphQL schema resolvers in this file.
For example:
<?php
namespace App\GraphQL\Queries;
use GraphQL\Type\Definition\ObjectType;
use App\Models\User;
class UserQuery
{
public function findByEmail(?ObjectType $rootValue, array $args): User
{
// validation logic
return User::where('email', $args['email'])->first();
}
}
Let's add the query logic inside schema.graphql
so we can query the User.
Note: the package functionality covers most use cases for queries.
Here is an example of a custom query, and resolver.
type Query {
user(
email: String!
): User @field(resolver: "App\\GraphQL\\Queries\\UserQuery@findByEmail")
}
field
directive will point user query to UserQuer@findByEmail
method and will pass email
as an argument.
Step 4: Test your GraphQL endpoint
Now that we’ve defined our GraphQL schema, we can test it by sending a GraphQL query to our Laravel application’s GraphQL endpoint.
You have to do a POST
request to {endpoint}/graphql
and define the query like this:
Query {
user(email: "test@test.com") {
id
name
}
}
Here we are making a query to our server to get User info (id, name), by email.
Conclusion
In this article, we’ve explored how to get started with Laravel and GraphQL, even if you’re a beginner. We’ve seen how GraphQL can simplify your API development and how to set up a basic GraphQL schema in Laravel. Of course, this is just the beginning of what you can do with Laravel and GraphQL. With a little more practice, you can create more complex schemas that can handle a wide range of data requirements.
So if you’re interested in developing APIs with Laravel and GraphQL, don’t be afraid to dive in and start exploring. There’s a lot to learn, but with a little effort, you can create powerful APIs that can handle any data requirements your application needs.
Check out my other stories
Please support me down below 👇