PHP code example of ayimdomnic / laragraph

1. Go to this page and download the library: Download ayimdomnic/laragraph library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ayimdomnic / laragraph example snippets


// app/GraphQL/Types/UserType.php
use Ayimdomnic\Laragraph\Support\Type;
use GraphQL\Type\Definition\Type as GType;

class UserType extends Type
{
    protected array $attributes = [
        'name'        => 'User',
        'description' => 'A registered user.',
    ];

    public function fields(): array
    {
        return [
            'id'    => ['type' => GType::nonNull(GType::id())],
            'name'  => ['type' => GType::string()],
            'email' => ['type' => GType::string()],
        ];
    }
}

// app/GraphQL/Queries/UsersQuery.php
use Ayimdomnic\Laragraph\Support\Query;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;

class UsersQuery extends Query
{
    public function type(): Type
    {
        return Type::listOf(app('laragraph')->type('User'));
    }

    public function args(): array
    {
        return [
            'limit' => ['type' => Type::int(), 'defaultValue' => 10],
        ];
    }

    public function resolve(mixed $root, array $args, mixed $context, ResolveInfo $info): mixed
    {
        return \App\Models\User::limit($args['limit'])->get();
    }
}

// app/GraphQL/Mutations/CreateUserMutation.php
use Ayimdomnic\Laragraph\Support\Mutation;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;

class CreateUserMutation extends Mutation
{
    public function type(): Type
    {
        return app('laragraph')->type('User');
    }

    public function args(): array
    {
        return [
            'name'  => ['type' => Type::nonNull(Type::string())],
            'email' => ['type' => Type::nonNull(Type::string())],
        ];
    }

    public function rules(array $args = []): array
    {
        return [
            'name'  => ['

'types' => [
    'User' => \App\GraphQL\Types\UserType::class,
],

'schemas' => [
    'default' => [
        'query'    => ['users' => \App\GraphQL\Queries\UsersQuery::class],
        'mutation' => ['createUser' => \App\GraphQL\Mutations\CreateUserMutation::class],
    ],
],

enum UserStatus: string
{
    case Active = 'active';

    #[\GraphQL\Type\Definition\Description('Suspended by a moderator.')]
    case Banned = 'banned';
}

// config/laragraph.php
'types' => ['UserStatus' => \App\Enums\UserStatus::class],

'graphiql' => [
    'enabled'    => true,                           // always serve it…
    'middleware' => ['auth', 'can:viewGraphiql'],   // …but only to trusted users
],

use Ayimdomnic\Laragraph\Pagination\ConnectionType;

class UsersQuery extends Query
{
    public function type(): Type
    {
        return new ConnectionType('UserConnection', app('laragraph')->type('User'));
    }

    public function args(): array
    {
        return ConnectionType::args(); // first, after, last, before
    }

    public function resolve(mixed $root, array $args, mixed $context, ResolveInfo $info): mixed
    {
        return ConnectionType::paginate(\App\Models\User::query(), $args);
    }
}

return ConnectionType::simplePaginate(\App\Models\User::query(), $args);
// → { data, total, per_page, current_page, last_page }

use Ayimdomnic\Laragraph\DataLoader\BatchResolver;

class UserLoader extends BatchResolver
{
    public function batch(array $keys): array
    {
        return User::whereIn('id', $keys)->get()->keyBy('id')->toArray();
    }
}

// In a resolver:
return $context->dataLoaders->get(UserLoader::class)->load($root->user_id);

// Works for any context type, including custom objects:
return DataLoaderRegistry::for($context)->get(UserLoader::class)->load($root->user_id);

class PostType extends Type
{
    public function fields(): array
    {
        return [
            'id'       => GType::nonNull(GType::id()),
            'comments' => GType::listOf(app('laragraph')->type('Comment')),
        ];
    }

    protected function resolveCommentsField(mixed $root, array $args, mixed $context): mixed
    {
        return $this->batchRelation(Post::class, 'comments', $root, $context);
    }
}

public function authorize(mixed $root, array $args, mixed $context, ResolveInfo $info): bool
{
    return $context->user()?->isAdmin() ?? false;
}

public function policy(): ?string { return PostPolicy::class; } // or Post::class
public function policyAbility(): string { return 'viewAny'; }

public function rules(array $args = []): array
{
    return ['email' => ['

use Ayimdomnic\Laragraph\Exceptions\GraphQLException;

throw new GraphQLException(
    key: 'errors.out_of_stock',       // lang/en/errors.php
    errorCode: 'OUT_OF_STOCK',
    replace: ['product' => $product->name],
);

// config/laragraph.php
'errors' => [
    'negotiate_locale'  => true,
    'supported_locales' => ['en', 'fr'],
],

'types' => [
    'DateTime' => \Ayimdomnic\Laragraph\Scalars\DateTimeType::class,
    'Date'     => \Ayimdomnic\Laragraph\Scalars\DateType::class,
    'JSON'     => \Ayimdomnic\Laragraph\Scalars\JsonType::class,
    'Upload'   => \Ayimdomnic\Laragraph\Scalars\UploadType::class,
],

'schemas' => [
    'default' => ['query' => [...], 'mutation' => [...]],
    'admin'   => ['query' => [...], 'mutation' => [...], 'middleware' => ['auth:api', 'admin']],
],

'security' => [
    'query_max_complexity'  => 500,
    'query_max_depth'       => 15,   // the standard introspection query needs 11
    'max_aliases'           => 30,   // blocks alias-flooding attacks
    'disable_introspection' => null, // null: disabled whenever app.debug is off
],

'cache' => [
    'response' => [
        'enabled' => true,
        'store'   => 'redis',
        'ttl'     => 60,
        'scope'   => 'user', // or 'global' when every caller gets identical data
    ],
],

'persisted_queries' => [
    'enabled' => true,
    'store'   => 'cache', // or 'array' with a static 'map'
    'apq'     => true,    // Automatic Persisted Queries registration
    'only'    => false,   // trusted-documents mode
],

'types' => ['Upload' => \Ayimdomnic\Laragraph\Scalars\UploadType::class],

// In mutation args:
'avatar' => ['type' => app('laragraph')->type('Upload')]

// In resolver — $args['avatar'] is \Illuminate\Http\UploadedFile
$path = $args['avatar']->store('avatars', 'public');

use Ayimdomnic\Laragraph\Facades\Laragraph;

$result = Laragraph::execute('{ users { id name } }');
$schema = Laragraph::schema('admin');
$type   = Laragraph::type('User');

'subscriptions' => ['enabled' => true],

// app/GraphQL/Subscriptions/UserCreatedSubscription.php
use Ayimdomnic\Laragraph\Support\Subscription;

class UserCreatedSubscription extends Subscription
{
    public function type(): Type
    {
        return app('laragraph')->type('User');
    }

    public function subscribe(mixed $root, array $args, mixed $context, ResolveInfo $info): mixed
    {
        return 'users'; // the channel clients subscribe to
    }

    public function resolve(mixed $root, array $args, mixed $context, ResolveInfo $info): mixed
    {
        return $root; // $root is the payload passed to Laragraph::broadcast()
    }
}

class CreateUserMutation extends Mutation
{
    public function resolve(mixed $root, array $args, mixed $context, ResolveInfo $info): mixed
    {
        $user = \App\Models\User::create($args);

        Laragraph::broadcast('users', $user);

        return $user;
    }
}

'tracing' => ['enabled' => true],
bash
php artisan vendor:publish --tag=laragraph-config
bash
php artisan laragraph:make:query UsersQuery
bash
php artisan laragraph:make:mutation CreateUserMutation