LoginSignup
1
0

More than 1 year has passed since last update.

Laravel で MongoDB のデータをテーブル表示

Last updated at Posted at 2018-06-12

次のプログラムを改造して、もう少し複雑なことをしてみます。
Laravel で MongoDB のデータを表示

次のようなテーブルの表示です。
cities_jun1201.png

MongoDB のデータは、

データベース: city
コレクション: saitama
です。

MongoDB のデータ

$ mongosh
(省略)
test> use city
switched to db city
city> db.saitama.find()
[
  {
    _id: ObjectId("61fcc4838ad033156d4d33c2"),
    key: 't1161',
    name: 'さいたま',
    population: 72136,
    date_mod: '2002-5-18'
  },
  {
    _id: ObjectId("61fcc4838ad033156d4d33c3"),
    key: 't1162',
    name: '所沢',
    population: 41378,
    date_mod: '2002-9-12'
  },

(省略)
city>

次の3つのファイルを編集します。

.env
app/Post.php
resources/views/index.blade.php

1) データベースの指定

次の行を編集

.env
// 略
DB_DATABASE=city
// 略

2) コレクションの指定

app/Post.php
<?php
namespace App;
class Post extends \Moloquent
{
    protected $collection = 'saitama';
}

3) テーブルの表示

resources/views/index.blade.php
<div>全部で{{ count($posts) }}件です</div>
<p />
<table>
  @foreach($posts as $post)
    <tr>
    <td>{{ $post['key']}}</td>
    <td>{{ $post['name']}}</td>
    <td>{{ $post['population']}}</td>
    <td>{{ $post['date_mod']}}</td>
    </tr>
  @endforeach
</table>

次の環境で確認しました。

$ uname -a
Linux iwata 5.13.0-27-generic #29-Ubuntu SMP Wed Jan 12 17:36:47 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

$ php --version
PHP 8.0.8 (cli) (built: Oct 26 2021 11:42:42) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.0.8, Copyright (c) Zend Technologies
    with Zend OPcache v8.0.8, Copyright (c), by Zend Technologies

$ php artisan --version
Laravel Framework 8.82.0
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0