MongoDB's flexible schema suits certain use cases. Laravel supports MongoDB through Eloquent, enabling NoSQL benefits with familiar syntax. At ZIRA Software, hybrid architectures leverage both MySQL and MongoDB strategically.
Installation
composer require mongodb/laravel-mongodb
Configure connection:
// config/database.php
'mongodb' => [
'driver' => 'mongodb',
'host' => env('MONGODB_HOST', '127.0.0.1'),
'port' => env('MONGODB_PORT', 27017),
'database' => env('MONGODB_DATABASE', 'homestead'),
'username' => env('MONGODB_USERNAME', ''),
'password' => env('MONGODB_PASSWORD', ''),
],
Models
use MongoDB\Laravel\Eloquent\Model;
class Post extends Model
{
protected $connection = 'mongodb';
protected $collection = 'posts';
protected $fillable = ['title', 'content', 'metadata'];
}
Usage
// Same as Eloquent
$post = Post::create([
'title' => 'MongoDB with Laravel',
'content' => 'Content here',
'metadata' => [
'tags' => ['laravel', 'mongodb'],
'views' => 0,
],
]);
// Query embedded documents
$posts = Post::where('metadata.tags', 'laravel')->get();
Hybrid Architecture
class User extends Authenticatable
{
protected $connection = 'mysql'; // Users in MySQL
}
class Activity extends Model
{
protected $connection = 'mongodb'; // Activity logs in MongoDB
}
Conclusion
MongoDB complements Laravel when flexibility matters. Use strategically for document storage and flexible schemas.
Considering MongoDB for your application? Contact ZIRA Software for database architecture consultation.