Docs Menu
Docs Home
/ / /
Laravel MongoDB
/

Write Data to MongoDB

1

Replace the store() method in the MovieController.php file, located in the app/Http/Controllers directory with the following code:

public function store(Request $request)
{
$data = $request->all();
$movie = new Movie();
$movie->fill($data);
$movie->save();
}
2

Generate an API route file by running the following command:

php artisan install:api

Tip

Skip this step if you are using Laravel 10.x because the file that the command generates already exists.

Import the controller and add an API route that calls the store() method in the routes/api.php file:

use App\Http\Controllers\MovieController;
// ...
Route::resource('movies', MovieController::class)->only([
'store'
]);
3

Update the Movie model in the app/Models directory to specify the fields that the fill() method populates as shown in the following code:

class Movie extends Model
{
protected $connection = 'mongodb';
protected $fillable = ['title', 'year', 'runtime', 'imdb', 'plot'];
}
4

Create a file called movie.json and insert the following data:

{
"title": "The Laravel MongoDB Quick Start",
"year": 2024,
"runtime": 15,
"imdb": {
"rating": 9.5,
"votes": 1
},
"plot": "This movie entry was created by running through the Laravel MongoDB Quick Start tutorial."
}

Send the JSON payload to the endpoint as a POST request by running the following command in your shell:

curl -H "Content-Type: application/json" --data @movie.json http://localhost:8000/api/movies
5

Open http://127.0.0.1:8000/browse_movies in your web browser to view the movie information that you submitted. The inserted movie appears at the top of the results.

Note

If you run into issues, ask for help in the MongoDB Community Forums or submit feedback by using the Rate this page tab on the right or bottom right side of the page.

Back

View MongoDB Data