30
loading...
This website collects cookies to deliver better user experience
.env.example
file to .env
, enter your Mongo credentials, and use it with php artisan serve
!OS -> Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-74-generic x86_64)
Laravel -> Laravel Framework 6.20.32
PHP -> PHP 7.4.3 (cli) (built: Jul 5 2021 15:13:35) ( NTS )
MongoDB -> 4.4.6
composer create-project laravel/laravel mongodb-sample "6.*"
pecl install mongodb
Composer require jenssegers/mongodb
use <DB Name>
db.post.insertOne({"body": "Orange","date": "2021-08-19"});
db.post.insertOne({"body": "Grape","date": "2021-08-22"});
db.post.insertOne({"body": "Apple","date": "2021-08-17"});
<?php
// ~Omitted~
'providers' => [
// Add the following to End.
Jenssegers\Mongodb\MongodbServiceProvider::class,
// ~Omitted~
'aliases' => [
// Add the following to End.
'Moloquent' => Jenssegers\Mongodb\Eloquent\Model::class,
<?php
// 'default' => env('DB_CONNECTION', 'mysql'),
'default' => env('DB_CONNECTION', 'mongodb'),
'connections' => [
// Added immediately after.
'mongodb' => [
'driver' => 'mongodb',
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
// If you have login restrictions, you also need the following.
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
],
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=xxxx
DB_USERNAME=xxxx
DB_PASSWORD=secret
# Delete the above and replace with the below, and enter the information as appropriate.
DB_CONNECTION=mongodb
DB_HOST=127.0.0.1
DB_PORT=27017
DB_DATABASE=xxxx
php artisan make:model Models/Post
/app/Models
, so please copy and paste all of the following and replace it.<?php
namespace App\Models;
use Jenssegers\Mongodb\Eloquent\Model as Moloquent;
class Post extends Moloquent
{
protected $collection = 'post';
}
php artisan make:controller TestController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class TestController extends Controller
{
static function index() {
$posts = Post::orderBy('_id', 'desc')->get();
return view('Test', ['posts' => $posts]);
}
}
foreach
.<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>MongoDB Show</title>
</head>
<body>
<div>Data Count:{{ count($posts) }}</div><br>
<!-- You can use the count() function to output the number of data in the collection. -->
<ul>
@foreach ($posts as $post)
<li>{{ 'Date:' . $post['date'] . ' | Value:' . $post['body'] }}</li>
@endforeach
</ul>
</body>
</html>
php artisan serve
, access http://localhost:8000/
, and if you can see it without any problems, successful!