Laravel is a popular web development framework for PHP. It offers many defaults and provides a code structure that is easy to understand and quick to use for implementing web applications and APIs. MongoDB has an official Laravel integration, available here on github. More information can be found in the official documentation.
In this tutorial, we will look at how you can use Laravel and MongoDB to build web applications and APIs.
Yes! In fact, MongoDB is a great choice for Laravel projects. As we get started with Laravel development using MongoDB, we'll work through an example of how to build a blog application.
The installation commands provided here were tested on MacOS, but you shouldn't run into issues if you're working in the Windows command line or on a Linux machine. You will need access to a MongoDB instance already running.
When developing a web application, you don’t want to spend a lot of time setting up and maintaining a database. Your local server may also have limited resources for storing data. MongoDB Atlas—MongoDB offered as a cloud service—is a great solution for this problem. You can create your cluster and database from a web console and connect to it from your Laravel application in just minutes. Atlas offers a free tier to get started with your Atlas experience.
(Feel free to code along or to download the full code from this GitHub repo.)
Since Laravel is a PHP framework, you will need to have PHP installed on your computer. The procedure may vary depending on your operating system. For more details on this step, please see the official installation documentation. For our walkthrough, you will need PHP version 7.4 installed on your computer.
The next step is to install Composer. Composer is a library and dependency manager for PHP, allowing you to add libraries that you may want to use in your project.
Once you have PHP and Composer installed, you can install Laravel.
From a terminal window, enter the following command:
composer global require "laravel/installer"
export PATH=$PATH:$HOME/.composer/vendor/bin
To start a Laravel project, run the following command. For our project, we'll use myapp
as the name of our application:
laravel new myapp
This creates a folder called myapp
, with the initial Laravel project structure inside of it.
If you run the following command from the myapp
folder, you should see a web application running with the initial Laravel page at http://localhost:8000:
cd myapp
php artisan serve
Before we can install the MongoDB libraries for Laravel, we need to install the PHP extension for MongoDB. Run the following command:
sudo pecl install mongodb
You will also need to ensure that the mongodb extension is enabled in your php.ini file. The location of your php.ini file will vary depending on your operating system. Add the following line to your php.ini file:
extension="mongodb.so"
Lastly, run the following command from your Laravel project directory in order to add the MongoDB package for Laravel:
composer require mongodb/laravel-mongodb
In order for Laravel to communicate with your MongoDB database, you will need to add your database connection information to the config\database.php file under the “connections” object in your Laravel project as shown in this example:
'connections' => [
'mongodb' => [
'driver' => 'mongodb',
'dsn' => env('DB_URI', 'mongodb+srv://username:password@<atlas-cluster-uri>/myappdb?retryWrites=true&w=majority'),
'database' => 'myappdb',
],
Make sure to include the correct authentication information.
Set the default database connection name in config\database.php:
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mongodb'),
If your Laravel project does not load dependencies automatically, you may also need to add the following to the provider’s section in your app.php file:
'providers' => [
/*
* Laravel Framework Service Providers...
*/
MongoDB\Laravel\MongoDBServiceProvider::class,
Laravel’s Eloquent library allows us to map and perform database CRUD operations (Create, Read, Update, Delete) directly from the Laravel models.
Assuming that we have a MongoDB collection called “posts,” an example document in the "posts" collection might look something like this:
{
"title":"First Blog Post",
"body" :"Lorem Ipsum, etc.",
"slug" :"first-blog-post"
}
If you are using MongoDB Atlas, you can use the Atlas Console to insert this document record directly into the database named “myappdb.”
Our first step will be to create a Laravel model to represent the blog posts. From the project directory, run the following command:
php artisan make:model Post -mc
This will create an App/Models/Post.php and an App/Http/Controllers/PostController.php file.
By default, artisan creates models that extend Illuminate\Database\Eloquent\Model.
However, for MongoDB, we want to extend the MongoDB Eloquent model, so we want to edit App/Models/Post.php. Our Post model ought to look like this:
namespace App\Models;
use MongoDB\Laravel\Eloquent\Model;
class Post extends Model
{
protected $connection = 'mongodb';
}
Note that when storing new data, Laravel will automatically create the collection in the MongoDB database for you. By default, the collection name is the plural of the model used (“posts” in this case). However, you can override that by setting a collection property on the model like this:
protected $collection = 'blog_posts';
If you were using multiple databases, you would also want to specify the database connection name on the model as indicated above.
Next, we can use our Post model to read and display our blog posts from the MongoDB database. First, let’s create a function in the PostController to get a blog post using a slug:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
public function show($slug)
{
return view('post', [
'post' => Post::where('slug', '=', $slug)->first()
]);
}
}
In the example above, we are just retrieving the post using its slug name. The MongoDB Eloquent models support all the standard Eloquent query methods, but they also support additional queries that are specific to MongoDB itself. For more details, see https://github.com/mongodb/laravel-mongodb.
Next, let’s add the following line to the routes\web.php file to create a route for the blog posts:
Route::get('/post/{slug}', [PostController::class, 'show']);
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/post/{slug}', [PostController::class, 'show']);
Finally, let’s add a view to format and style the blog post data for display. The view name needs to match the view that we use in our controller. We can do this by creating the file myapp/resources/views/post.blade.php with the following content:
<!DOCTYPE html>
<html>
<head>
<title>MyBlog</title>
</head>
<body>
<h1>{{$post->title}}</h1>
<div>{{$post->body}}</div>
</body>
</html>
Now we can see our post at http://localhost:8000/post/first-blog-post.
Now, let’s say you also wanted to create an API that you could use to create blog posts in your application. First, we would want to add a method in our PostController to store a post:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
public function show($slug)
{
return view('post', [
'post' => Post::where('slug', '=', $slug)->first()
]);
}
public function store(Request $request)
{
$post = new Post;
$post->title = $request->title;
$post->body = $request->body;
$post->slug = $request->slug;
$post->save();
return response()->json(["result" => "ok"], 201);
}
}
Next, we want to configure a resource route for posts in App\routes\api.php:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
Route::resource('posts', PostController::class)->only([
'destroy', 'show', 'store', 'update'
]);
And finally, we can test our API by making a POST request to http://localhost:8000/api/posts. Here’s an example using the Postman app:
Document
{
"title" : "Second Post",
"body" : "This is my second post.",
"slug" : "second-blog-post"
}
We can check the MongoDB database and see the blog post has been stored:
We should also be able to see the new post by going to http://localhost:8000/post/second-blog-post.
As you may have noticed, if a primary key is not specified on the model, the property _id is used as the primary key for each record.
To delete a record, we can use that id to find and delete records. Since we already defined a resource route for posts, we only need to add a destroy() method to the PostController:
public function destroy($postId)
{
$post = Post::find($postId);
$post->delete();
return response()->json(["result" => "ok"], 200);
}
Then, we can issue a DELETE request to the API endpoint http://localhost:8000/api/posts/<post_id> to delete a post.
We have created APIs to create and delete blog posts. We may also want to create an API for updating blog posts. This is very similar to the previous examples. We just need to add a method to the PostController:
public function update(Request $request, $postId)
{
$post = Post::find($postId);
$post->title = $request->title;
$post->body = $request->body;
$post->slug = $request->slug;
$post->save();
return response()->json(["result" => "ok"], 201);
}
Now, we can issue a PUT request to the API endpoint http://localhost:8000/api/posts/<post_id> with the updated content of the blog post.
Yes. The Laravel-MongoDB library integrates very well into the Laravel Eloquent model and allows developers to use MongoDB without additional effort.