Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

driesvints/graphql-shop

35 stars
4 code files
View driesvints/graphql-shop on GitHub

composer.json

Open in GitHub
{
//
"require": {
"php": "^7.4",
//
"mll-lab/laravel-graphql-playground": "^2.4",
"nuwave/lighthouse": "^4.18"
},
//
}

graphql/schema.graphql

Open in GitHub
"A date string with format `Y-m-d`, e.g. `2011-05-23`."
scalar Date @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\Date")
 
"A datetime string with format `Y-m-d H:i:s`, e.g. `2018-05-23 13:43:32`."
scalar DateTime @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTime")
 
type Query {
me: User @auth
orders: [Order!]! @paginate(defaultCount: 10)
products: [Product!]! @all
showCart: [Product!] @guard
users: [User!]! @paginate(defaultCount: 10)
user(id: ID @eq): User @find
}
 
type Mutation {
"Log in to a new session and get the user."
login(email: String!, password: String!): User!
 
"Log out from the current session, showing the user one last time."
logout: User @guard
addProductToCart(product: Int!): [Product!] @guard
purchaseProducts: Order! @guard
removeProductFromCart(product: Int!): [Product!] @guard
}
type User {
id: ID!
name: String!
email: String!
created_at: DateTime!
updated_at: DateTime!
orders: [Order!]! @hasMany
}
type Product {
id: ID!
name: String!
description: String!
price: Int!
created_at: DateTime!
updated_at: DateTime!
}
type Order {
id: ID!
total: Int!
created_at: DateTime!
updated_at: DateTime!
user: User! @belongsTo
products: [Product!]! @belongsToMany
}

app/GraphQL/Mutations/PurchaseProducts.php

Open in GitHub
use App\GraphQL\Exceptions\NoCartProducts;
use App\Models\Product;
use Illuminate\Support\Facades\Auth;
 
class PurchaseProducts
{
public function __invoke($_, array $args)
{
$user = Auth::user();
$products = Product::whereIn('id', (array) $user->cart)->get();
 
if ($products->isEmpty()) {
throw new NoCartProducts;
}
 
$order = $user->orders()->create(['total' => $products->sum(fn ($product) => $product->price)]);
 
$order->products()->sync($products);
 
$user->update(['cart' => []]);
 
return $order->refresh();
}
}

app/GraphQL/Exceptions/NoCartProducts.php

Open in GitHub
use Exception;
use Nuwave\Lighthouse\Exceptions\RendersErrorsExtensions;
 
class NoCartProducts extends Exception implements RendersErrorsExtensions
{
public function __construct()
{
parent::__construct('No products found in the user\'s cart.');
}
 
public function isClientSafe(): bool
{
return true;
}
 
public function getCategory(): string
{
return 'custom';
}
 
public function extensionsContent(): array
{
return [];
}
}