Help us understand the problem. What is going on with this article?

laravelのEloquentを使ってMySQLのデータを検索してみた

More than 1 year has passed since last update.

前回の続き

  • modelの作成
$ php artisan make:model City --migration
Model created successfully.
Created Migration: 2018_08_18_045057_create_cities_table

[プロジェクトルート]/app/City.phpが作成される

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    //
}
  • City.phpの修正
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    // テーブル名
    protected $table = 'city';
    // タイムスタンプ
    public $timestamps = false;
}
  • Controllerの修正
    • use Appの追加
    • MySQLからデータを取得し、Viewに渡す
use App;

    public function index()
    {
        $city = App\City::all();
        return view('world', ['city' => $city]);
    }
  • Viewの修正(一部抜粋)
    <?php foreach($city as $row) {
      echo '<tr>';
      echo '<td>'.htmlspecialchars($row['ID']).'</td>';
      echo '<td>'.htmlspecialchars($row['Name']).'</td>';
      echo '<td>'.htmlspecialchars($row['CountryCode']).'</td>';
      echo '<td>'.htmlspecialchars($row['District']).'</td>';
      echo '<td>'.htmlspecialchars($row['Population']).'</td>';
      echo '</tr>';
    }?>

参考

https://qiita.com/shosho/items/5ca6bdb880b130260586
https://readouble.com/laravel/

keb
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away