PHPackages                             mts88/mongogrid - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. mts88/mongogrid

ActiveLibrary[Database &amp; ORM](/categories/database)

mts88/mongogrid
===============

GridFS of MongoDB for Laravel

1.1.0(7y ago)72.7k4MITPHP

Since May 29Pushed 5y ago1 watchersCompare

[ Source](https://github.com/mts88/mongogrid)[ Packagist](https://packagist.org/packages/mts88/mongogrid)[ RSS](/packages/mts88-mongogrid/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (2)Versions (7)Used By (0)

Laravel MongoDB GridFS
======================

[](#laravel-mongodb-gridfs)

[![Latest Stable Version](https://camo.githubusercontent.com/0d127211c39e2c61f05cae26b8b18090c90f292717af3863a0153342124f9955/68747470733a2f2f706f7365722e707567782e6f72672f6d747338382f6d6f6e676f677269642f762f737461626c65)](https://packagist.org/packages/mts88/mongogrid)[![Total Downloads](https://camo.githubusercontent.com/4e4bd7680802f83909ccd35fad4eaf619156cb5dc577b6a0855c4a4e0fe2f46b/68747470733a2f2f706f7365722e707567782e6f72672f6d747338382f6d6f6e676f677269642f646f776e6c6f616473)](https://packagist.org/packages/mts88/mongogrid)[![License](https://camo.githubusercontent.com/61fe9dc655ae19210cc54605800dc0d21d6cb84c74d9b1828cb32b060aebda9f/68747470733a2f2f706f7365722e707567782e6f72672f6d747338382f6d6f6e676f677269642f6c6963656e7365)](https://packagist.org/packages/mts88/mongogrid)

A library wants to help the use of GridFS of MongoDB for Laravel 5. *This library extends the original [MongoDB GridFS Bucket for PHP](https://docs.mongodb.com/php-library/current/reference/class/MongoDBGridFSBucket/), so many methods are exactly the same and others are simplified for the use.*

#### Note

[](#note)

This is not a library for Eloquent or somenthing like this. It's a simple helper to easly use GridFS in Laravel. If you are looking for an Eloquent Model for MongoDB I suggest you [jenssegers/laravel-mongodb](https://github.com/jenssegers/laravel-mongodb).

Table of contents
=================

[](#table-of-contents)

- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
    - [Bucket Prefix](#bucket-prefix)
    - [Storing File](#storing-file)
    - [Get File](#get-file)
    - [Helpers](#helpers)
- [Contact](#contact)
- [License](#license)

Installation
============

[](#installation)

### Laravel version Compatibility

[](#laravel-version-compatibility)

LaravelPackage&lt; 5.5.x1.1.x (not tested)&gt;= 5.5.x1.1.x### Requirements

[](#requirements)

Make sure you have the MongoDB PHP driver installed. You can find installation instructions at

### Installation

[](#installation-1)

1. Installation using composer:

```
composer require mts88/mongogrid

```

2. And add the service provider in `config/app.php`:

```
Mts88\MongoGrid\Providers\MongoGridServiceProvider,
```

4. You may also register an alias for the MongoGrid library by adding the following to the alias array in `config/app.php`:

```
'MongoGrid'       => Mts88\MongoGrid\Facades\MongoGrid,
```

Configuration
-------------

[](#configuration)

Run the command below to publish the package config file `config/gridfs.php`:

```
php artisan vendor:publish
```

### MongoDB Connection

[](#mongodb-connection)

You can use build-in configuration in `config/gridfs.php` or you can use `config/database.php` (compatible with [jenssegers/laravel-mongodb](https://github.com/jenssegers/laravel-mongodb)).

#### Connection with config/gridfs.php

[](#connection-with-configgridfsphp)

In config file `config/gridfs.php` set up your configuration in order to connect to MongoDB:

##### Simple Connection

[](#simple-connection)

```
    'db_config' => [
        'host'     => env('DB_HOST', 'localhost'),
        'port'     => env('DB_PORT', 27017),
        'database' => env('DB_DATABASE'),
        'username' => env('DB_USERNAME'),
        'password' => env('DB_PASSWORD'),
        'options'  => [
            'database' => 'admin' // sets the authentication database required by mongo 3
        ]
    ],
```

##### ReplicaSet Connection

[](#replicaset-connection)

In your `.env` file add `DB_REPLICA_SET` property with the name of Replica Set

```
    'db_config' => [
        'host'     => [
            [
                'address' => 'server1',
                'port'=> 27017
            ],
            [
                'address' => 'server2',
                'port' => 27017
            ],
        ],
        'database' => env('DB_DATABASE'),
        'username' => env('DB_USERNAME'),
        'password' => env('DB_PASSWORD'),
        'options'  => [
            'replicaSet' => env('DB_REPLICA_SET'),
            'database' => 'admin' // sets the authentication database required by mongo 3
        ]
    ],
```

#### Connection with config/database.php

[](#connection-with-configdatabasephp)

In config file `config/gridfs.php` set up your configuration name:

```
'db_config' => env('DB_CONNECTION', 'mongodb'),
```

In config file `config/database.php` set up your configuration in order to connect to MongoDB: And add a new mongodb connection:

##### Simple Connection

[](#simple-connection-1)

```
'mongodb' => [
    'driver'   => 'mongodb',
    'host'     => env('DB_HOST', 'localhost'),
    'port'     => env('DB_PORT', 27017),
    'database' => env('DB_DATABASE'),
    'username' => env('DB_USERNAME'),
    'password' => env('DB_PASSWORD'),
    'options'  => [
        'database' => 'admin' // sets the authentication database required by mongo 3
    ]
],
```

##### ReplicaSet Connection

[](#replicaset-connection-1)

You can connect to multiple servers or replica sets with the following configuration:

```
'mongodb' => [
    'driver'   => 'mongodb',
    'host'     => ['server1', 'server2'],
    'port'     => env('DB_PORT', 27017),
    'database' => env('DB_DATABASE'),
    'username' => env('DB_USERNAME'),
    'password' => env('DB_PASSWORD'),
    'options'  => [
		'replicaSet' => 'replicaSetName'
	]
],
```

##### DSN URL

[](#dsn-url)

Alternatively, you can use MongoDB connection string:

```
'mongodb' => [
    'driver'   => 'mongodb',
    'dsn' => env('DB_DSN'),
    'database' => env('DB_DATABASE'),
],
```

Please refer to MongoDB official docs for its URI format:

#### Bucket Configuration

[](#bucket-configuration)

This is the config for GridFS Bucket:

```
    'bucket'    =>  [
        'prefix'            =>  'fs',
        'chunkSizeBytes'    =>  261120,
        'readPreference'    =>  'primaryPreferred',
        'readConcern'       =>  'available',
    ],
```

For more details see [MongoDB GridFS Bucket](https://docs.mongodb.com/php-library/current/reference/method/MongoDBGridFSBucket__construct/).

#### Metadata

[](#metadata)

By default the library adds these metadata to each document:

- uuid;
- created\_at;
- updated\_at;
- downloads;

set `false` in `config/gridfs.php` file to not include this info.

```
    'add_meta'      =>  false,
```

#### Temporary Storage

[](#temporary-storage)

By default the library use `local` driver for storing file into MongoDB. You can change the default driver of the `Storage`:

```
    'storage'       =>  'local',
```

To learn more see [Laravel File Storage](https://laravel.com/docs/5.6/filesystem).

Usage
-----

[](#usage)

### Bucket Prefix

[](#bucket-prefix)

By default MongoGrid use the prefix in `config/gridfs.php`, but if you want you can use another custom prefix on the fly:

```
MongoGrid::prefix('myNewPrefix')->someCoolMethod();
```

### Storing File

[](#storing-file)

#### storeFile( $fileContent, $fileName, \[ optional $metadata\] )

[](#storefile-filecontent-filename--optional-metadata-)

Store a file using contents, file name and your metadata (optional). Returns ObjectId

```
$fileName = 'differentName.jpg';
$fileContent = Storage::disk('local')->get('star-wars-logo.jpg');
$objectId = MongoGrid::storeFile($fileContent, $fileName);

// Or with your custom metadata

$fileName = 'differentName.jpg';
$fileContent = Storage::disk('local')->get('star-wars-logo.jpg');
$metadata = array(
	'father'	=>	'Anakin',
	'son'		=>	'Luke'
	);
$objectId = MongoGrid::storeFile($fileContent, $fileName, $metadata);
```

*Or using another prefix*

```
$fileName = 'differentName.jpg';
$fileContent = Storage::disk('local')->get('star-wars-logo.jpg');
$objectId = MongoGrid::prefix('starWars')->storeFile($fileContent, $fileName);

// Or with your custom metadata

$fileName = 'differentName.jpg';
$fileContent = Storage::disk('local')->get('star-wars-logo.jpg');
$metadata = array(
	'father'	=>	'Anakin',
	'son'		=>	'Luke'
	);
$objectId = MongoGrid::prefix('starWars')->storeFile($fileContent, $fileName, $metadata);
```

### Get File

[](#get-file)

All method to get files from GridFS. **Revision** numbers are defined as follows:

- 0 = the original stored file
- 1 = the first revision
- 2 = the second revision
- etc…
- -2 = the second most recent revision
- -1 = the most recent revision

> Defaults to -1 (i.e. the most recent revision). Revision works only on method by filename.

#### getFileContent( $source, \[optional $revision\] )

[](#getfilecontent--source-optional-revision-)

You can retrive the content of file by his name or his ObjectId. You can use also the revision of the file.

```
$fileName = 'star-wars-logo.jpg';
$content = MongoGrid::getFileContent($fileName, '-1');

// Or by ObjectId

$objectId = new \MongoDB\BSON\ObjectId;
$content = MongoGrid::getFileContent($objectId);
```

#### getFile( $source )

[](#getfile-source-)

You can retrive the content of file by his name or his ObjectId. Returns a document of the file collection.

```
$fileName = 'star-wars-logo.jpg';
$document = MongoGrid::getFile($fileName);

// Or by ObjectId

$objectId = new \MongoDB\BSON\ObjectId;
$document = MongoGrid::getFile($objectId);
```

#### findOne( $query, \[ optional $options \] )

[](#findone-query--optional-options--)

Finds a single document from the selected GridFS bucket matching the query.

```
$objectId = new \MongoDB\BSON\ObjectId;
$document = MongoGrid::findOne([ '_id' => $objectId ]);
```

To learn more about `$options` see [MongoDB GridFS findOne](https://docs.mongodb.com/php-library/current/reference/method/MongoDBGridFSBucket-findOne/).

#### find( $query, \[ optional $options \] )

[](#find-query--optional-options--)

Finds all documents from the selected GridFS bucket matching the query.

```
$objectId = new \MongoDB\BSON\ObjectId;
$document = MongoGrid::find([ '_id' => $objectId ]);
```

#### download( $source, string $path, \[optional $revision\] )

[](#download-source-string-path-optional-revision-)

Download a file from GridFS to a given path

```
$objectId = new \MongoDB\BSON\ObjectId;
$path = 'your/awesome/path';
MongoGrid::download($objectId, $path);

//Or by filename

$fileName = 'star-wars-logo.jpg';
$path = 'your/awesome/path';
MongoGrid::download($fileName, $path, '-1');
```

**NB:** downloading a file with this method will increments downloads on metadata by itself (only if metadata are active).

### Helpers

[](#helpers)

#### rename( $\_id, $newName )

[](#rename-_id-newname-)

Rename a file.

```
$objectId = new \MongoDB\BSON\ObjectId;
$newName = 'star-wars-amazing-logo.jpg';
MongoGrid::rename($objectId, $newName);
```

#### delete( $\_id )

[](#delete-_id-)

Delete a file from the collection.

```
$objectId = new \MongoDB\BSON\ObjectId;
MongoGrid::delete($objectId);
```

#### getBucketName()

[](#getbucketname)

Return the Collection Chunks of the selected GridFS Bucket

```
$bucketName = MongoGrid::getBucketName();
```

#### getChunksCollection()

[](#getchunkscollection)

Returns the name of the selected GridFS Bucket

```
$collection = MongoGrid::getChunksCollection();
```

#### getChunkSizeBytes()

[](#getchunksizebytes)

Return the size of Chunks of the selected GridFS Bucket

```
$size = MongoGrid::getChunkSizeBytes();
```

#### getDatabaseName()

[](#getdatabasename)

Return the name of the database used for selected GridFS

```
$databaseName = MongoGrid::getDatabaseName();
```

#### getFilesCollection()

[](#getfilescollection)

Return the Collection File of the selected GridFS Bucket

```
$collection = MongoGrid::getFilesCollection();
```

#### drop()

[](#drop)

Drop entire collections of a selected GridFS

```
MongoGrid::drop();
```

Contact
-------

[](#contact)

Open an issue on GitHub if you have any problems or suggestions.

License
-------

[](#license)

The contents of this repository is released under the [MIT license](http://opensource.org/licenses/MIT).

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity27

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 90.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~75 days

Total

5

Last Release

2611d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8beac3439ebe16044b86ab228f7c727898f17872140f47b7264455acf78ca103?d=identicon)[mts88](/maintainers/mts88)

---

Top Contributors

[![mts88](https://avatars.githubusercontent.com/u/6605380?v=4)](https://github.com/mts88 "mts88 (20 commits)")[![danitrap](https://avatars.githubusercontent.com/u/1345809?v=4)](https://github.com/danitrap "danitrap (1 commits)")[![msyahidin](https://avatars.githubusercontent.com/u/24245457?v=4)](https://github.com/msyahidin "msyahidin (1 commits)")

---

Tags

bucketdatabasedocumentfilegridgridfsgridfs-bucketlaravellaravel-mongodbmetadatamongomongodbmongogridselected-gridfsstoragelaravelfilestoragegridmongodbbucketmongoGridFSmongogrid

### Embed Badge

![Health badge](/badges/mts88-mongogrid/health.svg)

```
[![Health](https://phpackages.com/badges/mts88-mongogrid/health.svg)](https://phpackages.com/packages/mts88-mongogrid)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[leroy-merlin-br/mongolid

Easy, powerful and ultrafast ODM for PHP and MongoDB.

11234.3k4](/packages/leroy-merlin-br-mongolid)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
