LoginSignup
0
0

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-09-11

前回の続き

  • 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/

0
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
0
0