Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

betterMelon's avatar

How to handle MongoDB data in Laravel?

I just learned MongoDB, I learned it by itself not with Laravel. Right now I'm trying to learn how to work with it on Laravel. I tried to search a bit for answers and tried it myself, but I feel like I'm not satisfied with what I'm doing.

I think my main question right now is how do we handle data from MongoDB on Laravel? Because it feels a bit of unnatural when it comes to working with JSON in PHP, not that I have experienced much myself, but compared to JS it feels more natural there.

So, to start what I do is:

// Get the collection instance.
$collection = DB::connection('mongodb')->getCollection('users');

// Get the data from the collection instance.
$result = $collection->find();

// Loop through the cursor and put the data into an array.
$users = [];

foreach($result as $user) {
		array_push($users, $user);
}

// Now I have access to each of the document in the collection and I can do what I want with it.
return $users;

And to go back to my question, does it always have to be like this when handling MongoDB data?

I know that I could also use eloquent to build queries, but could I use the full potential of MongoDB if I go with this route?

I would really appreciate if someone could share other techniques or conventions when dealing with MongoDB.

0 likes
6 replies
betterMelon's avatar

@Tray2 Okay so, based from the guide, I'm gonna be using laravel's eloquent pretty much when I'm working with MongoDB.

1 like
nexxai's avatar

@betterMelon Yes, arguably one of Laravel's biggest strengths is Eloquent. That's not to say you can't write your own DB queries using something like the DB:: facade, but most people use a framework like Laravel precisely because it allows them to spend less time on the mechanics/solved problems like database queries so they can focus their time on the specific business idea they're trying to build.

2 likes
jlrdw's avatar

@betterMelon also and just FYI, node js with Express seems to me a good match with MongoDB.

Just my opinion, but with laravel I would stick with MySql.

2 likes
betterMelon's avatar

@nexxai Okay thanks, I guess I'm gonna really need to go the eloquent route if I'm sticking with Laravel as my main framework of choice.

betterMelon's avatar

@jlrdw Yeah, I kinda noticed, I started learning mongodb the past week and most tutorials are using Node.js with Express. I'm also fairly new to Laravel and I plan to stick with it as my first web app framework. I only picked up mongodb since it fits the needs for my project, I needed flexible columns, where each row of a table would have different columns. And since I'm still new to Laravel, I think its bad to jump to another framework this soon.

Please or to participate in this conversation.