Introduction to GraphQL with Laravel
GraphQL provides a flexible alternative to REST APIs. With Laravel and Lighthouse PHP, you can build powerful, type-safe APIs.
Step 1: Install Lighthouse
composer require nuwave/lighthouse
php artisan vendor:publish --tag=lighthouse-schema
Step 2: Define Your Schema
# graphql/schema.graphql
type Query {
users: [User!]! @paginate
user(id: ID! @eq): User @find
}
type User {
id: ID!
name: String!
email: String!
posts: [Post!]! @hasMany
}
type Post {
id: ID!
title: String!
content: String!
author: User! @belongsTo
}
Step 3: Mutations
type Mutation {
createUser(input: CreateUserInput! @spread): User! @create
updateUser(id: ID!, input: UpdateUserInput! @spread): User! @update
deleteUser(id: ID!): User! @delete
}
input CreateUserInput {
name: String!
email: String!
password: String! @hash
}
Step 4: Custom Resolvers
// app/GraphQL/Queries/UserQuery.php
class UserQuery
{
public function active($root, array $args)
{
return User::where('is_active', true)->get();
}
}
Step 5: Subscriptions
type Subscription {
postCreated: Post!
}
// Broadcasting the event
event(new PostCreated($post));
GraphQL with Laravel provides a powerful, flexible API layer for modern applications.
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!