CMS-agnostic GraphQL server in PHP. It follows the code-first approach, generating the schema dynamically GraphQL by PoP follows the code-first approach to generate the schema (it can be customized for different clients/applications). Graphql-php - A PHP port of GraphQL reference implementation. Railt - High quality and loosely coupled framework for developing GraphQL applications using all the modern qualities of the language. Digiaonline - Yet another PHP port of GraphQL reference implementation. Silos fs19. GraphQL (abandoned) - Well documented PHP implementation with no dependencies. Jul 16, 2018 GraphQL is a Query Language for the API’s or we can say GraphQL is an application layer query language. In short GraphQL is a modern way to fetch data from API calls. I called it a new or a modern way of consuming APIs, because it works on HTTP as REST works. In the first part of this tutorial we covered how you can setup GraphQL with PHP using Slim Framework. This part covers how to set up DataLoaderPHP for your field resolvers for query batching.
Introduction
If you're looking for a basic tutorial for using GraphQL with Laravel, you came to the right place. GraphQL has become a really helpful tool for us at Foster Made when we're developing Laravel applications. In my opinion, it provides a powerful and interesting concept that responds to challenges caused by the growing needs of better approaches for API development and a natural adaptation to advances in technology.
A brief background on GraphQL
Many of the advancements in technology today can be credited to major improvements in API architecture styles such as REST (Representational State Transfer). Preliminary outline. For the past decade, people have mostly been familiar with REST based APIs, but since the rise of APIs in the past years, newer challenges have risen. One major problem with REST APIs is that retrieving the data you want often requires multiple calls. An additional problem with REST APIs is their ability to adapt to multiple platforms. In 2012, Facebook started developing technology that goes by the name of “GraphQL” to help alleviate some of those challenges. The company then released it to the public in 2015.
GraphQL addresses known issues with REST by providing more flexibility to API clients to request only the data that they need at any given point in time while structuring it exactly the way it is intended to be used. In a nutshell, GraphQL is a platform-agnostic query language that describes how to ask for data and is generally used to load data from a server to a client. GraphQL comes with 3 main features: it allows the API client to specify what data it needs to consume, it facilitates the aggregation of data across multiple resources and nested resources, and it uses a type system to describe data.
GraphQL tutorial
Prerequisites
Before we begin, let's assume you have a basic knowledge of the Laravel framework. Let’s also assume that you have been through the official GraphQL website and went across this documentation. You should also ensure that you have PHP, SQLite, Composer as well as the Laravel installer already setup on your computer.
Create a new Laravel app
First we begin by creating a Laravel app using the Laravel installer:
In order to use GraphQL in this project, we will also import the “rebing/graphql-laravel” package via Composer.
Graphql Php Example
Once the package has been installed, we will need to copy the GraphQL package’s configuration files from the vendor directory to the application
Select the following providers from the list of possible providers by typing its corresponding number:
This will create the file: config/graphql.php which is the package configuration file.
Open that file and edit it as follows:
Open that file and edit it as follows:
In order to easily test our GraphQL App, we will also install GraphiQL ( An in-browser IDE for exploring GraphQL). We will import the “Nohac/laravel-graphiql” package to our application
Run the publish command again and this time, select the package for GraphiQL
Select the following providers from the list of possible providers by typing its corresponding number:
Create the Database
To makes this blog extremely simple to understand, we will focus on the User model that ships with the laravel package. Let’s ensure that you have default migration file located in the database/migrations/ folder.
Now, let’s create a seeder for the users database table
Then copy the following content to the UsersTableSeeder.php file located under the database/seeds/ folder.
Before running the migrations and seeders, you will need to ensure that your database credentials are properly set in the .env file, then you would execute the following commands:
After a successful execution, you should have 10 fake user accounts in your database.
Finally, Add the following function to the user model to make it easier to encrypt passwords via GraphQL mutations.
Define the GraphQL Schema
In order to start using the GraphQL package, we need to define the schema. In general, schemas describe how data are structured and what data on the server can be retrieved via GraphQL. Schemas consist of GraphQL Queries and Mutations. The difference between a GraphQL query and a mutation is that a query is used to fetch data while mutation is used for INSERT/UPDATE/DELETE operations. Also, the data returned once a query or mutation is executed is structured based on the GraphQL type corresponding to the object or collection of objects being returned.
Schemas are defined inside the config/graphql.php file in order to describe how data are shaped (via GraphQL types) and what data on the server can be queried or mutated.
Let’s create a GraphQL folder under our app directory, then create 3 folders under it which are Queries, Mutations and Types.
Creating a GraphQL Type
The most basic components of a GraphQL schema are object types, which just represent a kind of object you can fetch from your service, and what fields it has. In the GraphQL schema language, we might represent the user type like this:
As you can notice, the “User” type defined here is a custom type that contains 3 fields (id, name, email). Those fields could be of a scalar type or another custom type.
Visit plex.tv and choose Sign In (or Sign Up if you are a new user) 2. Sign in using one of the methods below 3. After signing in or signing up, choose My Account in the upper right-hand corner 4. Click Downloads 5. Choose the Media Server for your device and click Download 6. Jan 02, 2020 How to Set Up a Plex Server Pick the Hardware You Want to Run On. Some people choose to use a dedicated Network Attached Storage (NAS) device to. Install the Plex Media. Once you've picked which hardware you're going to use, download the Plex Media Server. Set Up Your Libraries. Dec 09, 2019 Best NAS for Plex Options: Plex NAS Devices. QNAP TS-453Be 4-Bay Professional NAS. QNAP TS-453Be-4G-US (4GB RAM Version) 4-Bay Professional NAS. Intel Celeron Apollo Lake J3455 Quad-core CPU. Synology DS218play. TerraMaster F4-220 4-Bay NAS. Plex server update.
GraphQL comes with a set of default scalar types out of the box:
- Int: A signed 32‐bit integer.
- Float: A signed double-precision floating-point value.
- String: A UTF‐8 character sequence.
- Boolean: true or false.
- ID: The ID scalar type represents a unique identifier, often used to refetch an object or as the key for a cache. The ID type is serialized in the same way as a String; however, defining it as an ID signifies that it is not intended to be human‐readable.
In the GraphQL schema language, the exclamation mark (!) indicates that a field is non-null.
Now, let’s represent this GraphQL type in corresponding PHP format. Below is the code snippet:
Create GraphQL Queries and Mutations
As specified before, queries are simply used to retrieve some info. A query essentially returns a GraphQL type, or an array of a specified type. Let’s update the config/graphql.php file as follows to define 2 queries which are “user” and “users”, as well as specifying the GraphQL type “User” that was previously created.
Once the queries have been defined, we can actually create them in the GraphQL folder at the following location app/graphql/queries/ while the types will be created at placed in the app/graphql/types/ folder.
A basic User Query could be as follows:
A basic User Query could be as follows:
The users query which retrieves a collection of users would be as follows:
Please note that you could also use eager loading feature to improve the performance of your GraphQL queries. Also, you can use the pagination feature to limit results on queries returning large datasets.
In the examples above, we have defined 5 functions which are:
- authorize: used to define some logic to authorize the user making the query request to retrieve the data requested
- type: used to define the GraphQL type that should be returned by the query
- rules: used to define validation rules against the arguments passed to the query
- args: used to defined the arguments that should or could be passed along with the query. These arguments are validated against the validation rules specified in the rules function
- resolve: used to define the necessary logic to retrieve the Laravel model or collection to return. The result should correlate to the GraphQL type specified in the type function.
Mutations are pretty similar to queries. The only difference is that, the resolve function of a mutation contains logic to modified the targeted object.
Let’s add a CreateUserMutation, UpdateUserMutation and DeleteUserMutation to our GraphQL config file as follows:
These mutations should be saved in the app/graphql/mutations as follows:
And finally, a DeleteUserMutation would look like this:
Note that for the DeleteUserMutation, we chose to return the scalar type “boolean” which would be true if the deletion has been successful or false otherwise.
Execute Queries or Mutations
Start the application by running the following command
Then go to the following URL: http://127.0.0.1:8000/graphql-ui. You should see the graphiql interface. Type the following query in the left pane and click on the submit button (Play icon) to preview the results.
You should expect something like this:
You should also be able to execute any of the mutations in a similar fashion. Let’s create a new user by executing the following
The expected result should look like this:
Now that you are able to execute GraphQL queries and mutations, try to execute queries or mutations to see how to react based on constraints set in the validation rules. Also, feel free to try to paginated or eager load some responses. Finally, add more eloquent relationships to the User model and link them via GraphQL types as well.
Conclusion
So there you have it, GraphQL and Laravel. It might seem intimidating at first because it definitely comes with quite a few conceptual ideas, but if you take the time to understand the underlying concepts, I think you’ll realize that it all funnels through. Whether you decide on hopping on this GraphQL journey or not, I believe it will continue to gain in popularity as more and more companies get accustomed to it, and it might very well be on the verge to becoming one of the essential building blocks of the web in the upcoming future.
Feel free to download a more complete example we put together at the following link.
![Php Php](/uploads/1/3/7/4/137402788/709791981.png)
Cached
Posted in #Technologies under *Laravel, *PHP, *GraphQL
Recent Posts
Sharing what we learn and love
Our Design Process at a Glance
By Haley Stonecipher
Laughing our way out of 2020 with gratitude
By Nina Rogers