Laravel is a popular PHP web application framework that provides a robust and elegant toolkit for building modern web applications. MongoDB, on the other hand, is a NoSQL document database that allows for flexible and scalable data storage.
If you want to use MongoDB with Laravel, you can use the Laravel MongoDB package, which is an open-source package that provides a MongoDB-based driver for Laravel’s Eloquent ORM. This package allows you to use the same syntax and functionality you are used to with Eloquent, but with a MongoDB backend.
To use Laravel MongoDB in your Laravel project, you can follow these steps:
- Install the package using Composer:
composer require jenssegers/mongodb
- Configure the MongoDB connection in the
config/database.php
file:
'mongodb' => [
'driver' => 'mongodb',
'host' => env('MONGODB_HOST', 'localhost'),
'port' => env('MONGODB_PORT', 27017),
'database' => env('MONGODB_DATABASE'),
'username' => env('MONGODB_USERNAME'),
'password' => env('MONGODB_PASSWORD'),
],
- Create a new model that extends the
Jenssegers\Mongodb\Eloquent\Model
class:
use Jenssegers\Mongodb\Eloquent\Model;
class User extends Model
{
protected $connection = 'mongodb';
protected $collection = 'users';
}
- Use the model in your controller or other parts of your application just like you would with a regular Eloquent model:
$user = new User;
$user->name = 'John Doe';
$user->email = 'john@example.com';
$user->save();
$users = User::where('name', 'John Doe')->get();
Laravel Mongodb test connection
To test the connection to MongoDB in Laravel, you can use the following steps:
- Open your Laravel project and navigate to the
.env
file in the root directory. - Add the MongoDB connection details to the
.env
file, such as the database name, MongoDB host, and port number.
For example:
MONGODB_HOST=localhost
MONGODB_PORT=27017
MONGODB_DATABASE=mydatabase
MONGODB_USERNAME=myusername
MONGODB_PASSWORD=mypassword
- Open the terminal or command prompt and navigate to your Laravel project’s root directory.
- Run the following command to create a new Laravel migration:
php artisan make:migration test_mongodb_connection
- Open the newly created migration file located in the
database/migrations
directory. - Add the following code to the
up()
method of the migration:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;
use Jenssegers\Mongodb\Connection;
class TestMongodbConnection extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$connection = new Connection(config('database.connections.mongodb'));
try {
$connection->getMongoClient();
echo "Successfully connected to MongoDB!";
} catch (Exception $e) {
echo "Failed to connect to MongoDB: " . $e->getMessage();
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
// Nothing to do here
}
}
- Save the migration file and return to the terminal or command prompt.
- Run the following command to run the migration and test the connection to MongoDB:
php artisan migrate --path=/database/migrations/2023_03_05_000000_test_mongodb_connection.php
This command will execute the up()
method of the migration, which will attempt to connect to MongoDB and print a message indicating whether the connection was successful or not.
By following these steps, you can test the connection to MongoDB in your Laravel application.
Laravel Mongodb package
The Laravel MongoDB package is an open-source package that provides a MongoDB-based driver for Laravel’s Eloquent ORM. It allows you to use MongoDB as the backend database for your Laravel application.
Here are some of the features provided by the Laravel MongoDB package:
- MongoDB-based driver for Laravel’s Eloquent ORM: The package provides a MongoDB-based driver for Laravel’s Eloquent ORM, allowing you to use the same syntax and functionality you are used to with Eloquent, but with a MongoDB backend.
- Support for MongoDB-specific features: The package includes support for MongoDB-specific features such as geo-spatial indexing and querying, which are not available in traditional SQL databases.
- Support for MongoDB’s aggregation framework: The package provides support for MongoDB’s aggregation framework, allowing you to perform complex queries and data analysis on your MongoDB data.
- Seamless integration with Laravel: The package integrates seamlessly with Laravel, allowing you to use Laravel’s familiar syntax and functionality for MongoDB-based applications.
To install the Laravel MongoDB package, you can use Composer by running the following command in your Laravel project’s root directory:
composer require jenssegers/mongodb
Once installed, you can use the Laravel MongoDB package by creating a new model that extends the Jenssegers\Mongodb\Eloquent\Model
class, and configuring the MongoDB connection details in the config/database.php
file. Then, you can use the model in your application just like you would with a regular Eloquent model.
For more information on how to use the Laravel MongoDB package, you can refer to the package’s documentation at https://github.com/jenssegers/laravel-mongodb.
Laravel Mongodb migrations example
Let’s say you want to create a books
collection in MongoDB to store information about books in your application. Here’s how you would create a migration for it:
- Run the following command in your terminal to create a new migration file:
php artisan make:migration create_books_collection --table=books --create
This command will create a new migration file with the name create_books_collection
in the database/migrations
directory.
- Open the newly created migration file and modify the
up()
method to create the fields you want in your MongoDB collection, using the Schema facade:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;
use Jenssegers\Mongodb\Schema\Blueprint;
class CreateBooksCollection extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::connection('mongodb')->create('books', function (Blueprint $collection) {
$collection->index('title');
$collection->string('title');
$collection->string('author');
$collection->text('description')->nullable();
$collection->integer('year_published');
$collection->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::connection('mongodb')->drop('books');
}
}
This example creates a MongoDB collection named “books” with fields for title, author, description, year_published and timestamps. The Blueprint
class is provided by the Laravel MongoDB package and is used to create the fields in the collection.
- Run the migration using the following command:
php artisan migrate
This will create the MongoDB collection specified in the migration.
- To roll back a migration, use the following command:
php artisan migrate:rollback
This command will reverse the last migration that was run.
By following these steps, you can use Laravel’s migration functionality to manage MongoDB collections in your Laravel application using the Laravel MongoDB package.
Comments