slogan3

Implementeer een GraphQL API in Laravel met Lighthouse

description

Deze prompt helpt je om een krachtige en flexibele GraphQL API te implementeren in jouw Laravel project. Je leert hoe je Lighthouse optimaal inzet voor efficiënte dataquery's en hoe je veilige toegang realiseert met authentificatie. Dit resulteert in een toekomstbestendige API die makkelijk schaalbaar en aanpasbaar is.

prompt

Help mij een flexibele GraphQL API in mijn Laravel project te integreren met Lighthouse. Geef aan hoe ik query's en mutaties kan structureren voor de specifieke entiteit: <Specifieke Entiteit> (bijv. gebruikers, prod ...

try_prompt

generate_helper
disclaimerOnPageApi

ai_answers

provider: openai
model: gpt-4.1-nano
Zeker! Hier is een overzicht van hoe je een flexibele GraphQL API in Laravel met Lighthouse kunt opzetten, inclusief structuur voor query's, mutaties, velddefinities, resolvers en authenticatie via JWT. --- ### 1. Installatie en setup van Lighthouse Voer de volgende commando's uit: ```bash composer require nuwave/lighthouse php artisan vendor:publish --provider="Nuwave\Lighthouse\LighthouseServiceProvider" ``` Configureer je `.env` voor JWT-authenticatie (bijvoorbeeld met `laravel/sanctum` of `tymon/jwt-auth`). ### 2. Definieer je GraphQL schema Maak een `graphql/schema.graphql` bestand. Hier definieer je je entiteiten en operaties: ```graphql type Gebruiker { id: ID! naam: String! email: String! producten: [Product!]! @hasMany } type Product { id: ID! naam: String! prijs: Float! eigenaar: Gebruiker! @belongsTo } type Query { alleGebruikers: [Gebruiker!]! @auth gebruiker(id: ID!): Gebruiker @auth alleProducten: [Product!]! @auth product(id: ID!): Product @auth } type Mutation { registreerGebruiker(naam: String!, email: String!, wachtwoord: String!): Gebruiker @create login(email: String!, wachtwoord: String!): String @field(resolver: "App\\GraphQL\\Mutations\\AuthMutator@login") voegProductToe(naam: String!, prijs: Float!): Product @auth } ``` ### 3. Resolvers en mutators Voor complexe logica zoals login, maak je een mutator: ```php namespace App\GraphQL\Mutations; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use App\Models\User; class AuthMutator { public function login($root, array $args) { $user = User::where('email', $args['email'])->first(); if (!$user || !Hash::check($args['wachtwoord'], $user->wachtwoord)) { throw new \Exception('Ongeldige inloggegevens'); } return auth()->login($user) ? auth()->user()->createToken('JWT')->plainTextToken : null; } } ``` Voor eenvoudige CRUD operaties gebruik je de `@create`, `@update`, `@delete` directives, of definieer je resolvers. ### 4. Authenticatie via JWT - Installeer JWT-auth: ```bash composer require tymon/jwt-auth php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" php artisan jwt:secret ``` - Configureer `config/jwt.php` en `auth.php` voor JWT. - Voeg middleware toe: ```php // In `app/Http/Kernel.php` protected $middlewareGroups = [ 'api' => [ 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, 'auth:api', // Gebruik JWT guard ], ]; ``` - In `config/auth.php`, zet de guard: ```php 'guards' => [ 'api' => [ 'driver' => 'jwt', 'provider' => 'users', ], ], ``` ### 5. Voorbeeld query en mutatie **Query:** ```graphql query { alleGebruikers { id naam email producten { id naam prijs } } } ``` **Mutatie:** ```graphql mutation { voegProductToe(naam: "Nieuwe Laptop", prijs: 1200.50) { id naam prijs } } ``` **Inloggen:** ```graphql mutation { login(email: "test@example.com", wachtwoord: "secret") } ``` De `login` mutation geeft een JWT token terug dat je in headers (Authorization: Bearer <token>) gebruikt voor beveiligde requests. --- ### Samenvatting - Definieer je entiteiten en operaties in `schema.graphql`. - Gebruik directives (@auth, @create, @belongsTo, @hasMany) voor structuur en beveiliging. - Implementeer complexe logica in mutators. - Beveilig je API met JWT door middleware in te stellen. - Gebruik query's en mutaties voor CRUD en authenticatie. Wil je hulp met specifieke modellen, resolvers of configuratie?
provider: deepseek
model: deepseek-chat
Zeker, ik help je graag met het integreren van Lighthouse voor een flexibele GraphQL API in Laravel. Hier is een complete handleiding: ## 1. Installatie en Setup ```bash composer require nuwave/lighthouse php artisan vendor:publish --tag=lighthouse-schema php artisan vendor:publish --tag=lighthouse-config ``` ## 2. JWT Authenticatie Installatie ```bash composer require tymon/jwt-auth php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" php artisan jwt:secret ``` ## 3. GraphQL Schema Definitie (graphql/schema.graphql) ```graphql type User { id: ID! name: String! email: String! created_at: DateTime! updated_at: DateTime! } type Query { users: [User!]! @all user(id: ID! @eq): User @find me: User @auth } type Mutation { createUser( name: String! @rules(apply: ["required", "min:3"]) email: String! @rules(apply: ["required", "email", "unique:users"]) password: String! @rules(apply: ["required", "min:6"]) ): User @create updateUser( id: ID! name: String @rules(apply: ["min:3"]) email: String @rules(apply: ["email"]) ): User @update deleteUser(id: ID!): User @delete login(email: String!, password: String!): String logout: String @auth } ``` ## 4. Model en Migratie **database/migrations/xxxx_xx_xx_create_users_table.php** ```php public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->timestamps(); }); } ``` **app/Models/User.php** ```php <?php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Tymon\JWTAuth\Contracts\JWTSubject; class User extends Authenticatable implements JWTSubject { protected $fillable = ['name', 'email', 'password']; protected $hidden = ['password']; public function getJWTIdentifier() { return $this->getKey(); } public function getJWTCustomClaims() { return []; } } ``` ## 5. Custom Resolver voor Authenticatie **app/GraphQL/Mutations/Login.php** ```php <?php namespace App\GraphQL\Mutations; use Illuminate\Support\Facades\Auth; use Tymon\JWTAuth\Facades\JWTAuth; class Login { public function __invoke($rootValue, array $args) { $credentials = [ 'email' => $args['email'], 'password' => $args['password'] ]; if (!$token = Auth::guard('api')->attempt($credentials)) { throw new \Exception('Ongeldige inloggegevens'); } return $token; } } ``` **app/GraphQL/Mutations/Logout.php** ```php <?php namespace App\GraphQL\Mutations; use Tymon\JWTAuth\Facades\JWTAuth; class Logout { public function __invoke($rootValue, array $args) { JWTAuth::invalidate(JWTAuth::getToken()); return 'Uitgelogd'; } } ``` ## 6. Configuratie (config/lighthouse.php) ```php return [ 'security' => [ 'max_query_complexity' => 1000, 'max_query_depth' => 20, ], 'namespaces' => [ 'models' => ['App\\Models', 'App'], 'queries' => ['App\\GraphQL\\Queries'], 'mutations' => ['App\\GraphQL\\Mutations'], ], ]; ``` ## 7. Authenticatie Middleware Voeg in **config/lighthouse.php**: ```php 'middleware' => [ \Nuwave\Lighthouse\Support\Http\Middleware\AcceptJson::class, \Illuminate\Cookie\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \Nuwave\Lighthouse\Support\Http\Middleware\AttemptAuthentication::class, ], ``` ## 8. Voorbeeld Query's en Mutaties ### Authenticatie Mutatie: ```graphql mutation Login { login(email: "gebruiker@voorbeeld.nl", password: "wachtwoord123") } ``` ### Gebruikers Query's: ```graphql query GetAllUsers { users { id name email created_at } } query GetUser { user(id: 1) { id name email } } query GetMe { me { id name email } } ``` ### Gebruikers Mutaties: ```graphql mutation CreateUser { createUser( name: "Nieuwe Gebruiker" email: "nieuw@voorbeeld.nl" password: "geheim123" ) { id name email } } mutation UpdateUser { updateUser( id: 1 name: "Bijgewerkte Naam" email: "bijgewerkt@voorbeeld.nl" ) { id name email } } mutation DeleteUser { deleteUser(id: 1) { id name } } mutation Logout { logout } ``` ## 9. Authorization Policies **app/Policies/UserPolicy.php** ```php <?php namespace App\Policies; use App\Models\User; class UserPolicy { public function view(User $authenticatedUser, User $user) { return $authenticatedUser->id === $user->id; } public function update(User $authenticatedUser, User $user) { return $authenticatedUser->id === $user->id; } public function delete(User $authenticatedUser, User $user) { return $authenticatedUser->id === $user->id; } } ``` ## 10. Gebruik in Schema ```graphql type Query { user(id: ID! @eq): User @find @can(ability: "view", find: "id") } type Mutation { updateUser( id: ID! name: String email: String ): User @update @can(ability: "update", find: "id") } ``` ## 11. Testen met Headers Vergeet niet de JWT token mee te sturen in requests: ```http Authorization: Bearer YOUR_JWT_TOKEN Content-Type: application/json ``` Deze setup biedt een complete, veilige GraphQL API met JWT authenticatie voor gebruikersbeheer in Laravel met Lighthouse.