Uploading multiple files in Laravel Lighthouse GraphQL

Wai Hein
2 min readJun 26, 2020

First thing first, let me introduce myself. I am an experienced Software Engineer currently based in the UK. I am originally from Myanmar and I also used to work in Myanmar and Singapore as Full-Stack Software Engineer before I moved to the UK. If you want to reach me out, here is my LinkedIn profile, https://www.linkedin.com/in/wai-yan-hein-b99162123/.

This article will show you how to upload multiple files in GraphQL using Lighthouse library in Laravel. I assume you have basic knowledge about Laravel, GraphQL and Lighthouse PHP library.

This is the library we are using, https://lighthouse-php.com/. You will need to follow the installation guide on the documentation to integrate the library with the Laravel.

Let’s jump straight to the point and get our hands dirty. In order to upload multiple files, the first thing we have to do is declaring mutation in the schema as follow.

scalar Upload @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\Upload")extend type Mutation {
uploadFiles(logoImageFile: Upload!, coverImageFile: Upload!): String
}

Take note that we import the `Upload` scalar type.

Then we will need to create a mutation for that running the following command.

php artisan lighthouse:mutation UploadFiles

Then, a mutation class will be created and we can implement the file upload logic there.

The following is the dummy code showing how to upload the files.

<?php

namespace App\GraphQL\Mutations;

class UploadTestFile
{
/**
*
@param null $_
*
@param array<string, mixed> $args
*/
public function __invoke($_, array $args)
{
$logoImageFile = $args['logoImageFile'];
$coverImageFile = $args['coverImageFile'];
$logoImageFile->storePublicly('uploads');
$coverImageFile->storePublicly('uploads');

// TODO implement the resolver
}
}

If you are writing tests, you can make the request as follow.

$this->multipartGraphQL(
[
'operations' => /** @lang JSON */
'
{
"query": "mutation Upload($logoImageFile: Upload!, $coverImageFile: Upload!) { uploadFiles(logoImageFile: $logoImageFile, coverImageFile: $coverImageFile) }",
"variables": {
"logoImageFile": null,
"coverImageFile": null
}
}
',
'map' => /** @lang JSON */
'
{
"0": ["variables.logoImageFile"],
"1": ["variables.coverImageFile"]
}
',
],
[
'0' => UploadedFile::fake()->create('logo.jpg', 500),
'1' => UploadedFile::fake()->create('cover.jpg', 500),
]
);

That’s it. That is how we upload multiple files in GraphQL for Laravel application. Hope this article is helpful.

--

--

Wai Hein

8 x AWS Certified Full-stack | DevOps | Serverless Engineer with over a decade of experience