How to remove a file from Google Drive using Laravel?

I’ve got a problem with deleting files from Google Drive in my Laravel app. Here’s what I’m doing:

// Uploading file
$request->document->storeAs('my-folder-id', $filename, 'google');

// Getting file URL
$fileUrl = Storage::disk('google')->url('my-folder-id/' . $filename);

This works fine for uploading. But when I try to delete the file, nothing happens. I’ve tried these:

$attachment = FileAttachment::find($id);
$fileExists = Storage::disk('google')->has('my-folder-id/' . $attachment->filename);
$deleteResult = Storage::disk('google')->delete('my-folder-id/' . $attachment->filename);

Both $fileExists and $deleteResult are always false. What am I doing wrong? Is there a different way to remove files from Google Drive using Laravel? Any help would be great!

I’ve encountered this issue before, and it can be tricky. The problem likely stems from how Laravel’s Storage facade interacts with Google Drive’s file system. Instead of using the standard Storage methods, you might want to leverage the Google Drive API directly for more reliable file management.

Here’s an approach that’s worked for me:

  1. Install the Google API Client Library for PHP.
  2. Set up proper authentication with a service account.
  3. Use the Drive service to interact with files.

For deletion, you’d do something like this:

$driveService = new Google_Service_Drive($client);
$driveService->files->delete($fileId);

This method gives you more control and better error handling. Just make sure to store the file ID when you initially upload the file. It’s a bit more work upfront, but it’s much more robust in the long run.

hey mate, have u tried using the google_drive_file_id instead of the filename? sometimes the api can be picky bout that. u could try somethin like:

$fileId = $attachment->google_drive_file_id;
$deleteResult = Storage::disk(‘google’)->getAdapter()->delete($fileId);

make sure u save the file id when uploading. hope this helps!

I’ve dealt with similar issues when working with Google Drive in Laravel. The problem might be in how you’re referencing the file path. When using Google Drive, the file ID is more reliable than the path.

Try this approach instead:

When uploading the file, store the file ID returned by Google Drive. Then, to delete the file, use the file ID directly.

Here’s a rough example:

// Uploading
$adapter = Storage::disk('google')->getAdapter();
$response = $adapter->write('my-folder-id/' . $filename, $fileContent);
$fileId = $response['path'];

// Deleting
$adapter = Storage::disk('google')->getAdapter();
$adapter->delete($fileId);

This method bypasses the abstraction layer and works directly with the Google Drive adapter. It’s been more reliable in my experience. Remember to handle exceptions and validate the file ID before deletion.