LoginSignup
1
0

More than 5 years have passed since last update.

PHPのlaravelでMySQLのデータベースにアクセスしてみた

Last updated at Posted at 2018-08-25

前回の続き

環境

  • Mac High Sierra 10.13.5
  • PHP 7.1.16
  • composer 1.5.6
  • laravel 5.6.33

設定変更

  • パーミション変更
    参考によれば、パーミッションを変更したほうが良さそうなので、変更
$ chmod 777 bootstrap/cache
$ chmod 777 storage

コントローラーとビュー作成

  • コントローラー作成
    以下コマンドでリソースコントローラを作成
$ php artisan make:controller WorldController --resource
Controller created successfully.

[プロジェクトルート]/app/Http/ControllersにWorldController.phpが作成されている

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class WorldController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

一部修正。これでviewに飛ばす。

    public function index()
    {
        return view('world');
    }

なお、artisan は Laravel に含まれているユーティリティーコマンドみたいです。
コマンド一覧は以下で確認可能

$ php artisan list
  • コントローラーへのルートを登録
    [プロジェクトルート]/routes/web.phpの最終行に追加
    /worldときたらコントローラーへ飛ばす
<?php

Route::get('/', function () {
    return view('welcome');
});

Route::resource('world', 'WorldController');
  • View作成
    [プロジェクトルート]/resources/views/world.blade.php作成
<!doctype html>
<html>
  <body>
    <h1> Hello World </h1>
  </body>
</html>
  • 起動
$ php artisan serve
Laravel development server started: <http://127.0.0.1:8000>

これで、http://127.0.0.1:8000/world にアクセスしてHello Worldと表示されればOK。

データベース作成

  • データベースの作成
    データベースはMySQLを使用する
    MySQLのバージョン確認
$ mysql -V
mysql  Ver 8.0.12 for osx10.13 on x86_64 (Homebrew)
  • MySQLのサイトからサンプルーデータ(world database)をダウンロードして登録
  • worldユーザを作成する
$ mysql.server start
Starting MySQL
 SUCCESS!
$ mysql -u root -p < world.sql
$ mysql -u root -p

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| world              |
+--------------------+
5 rows in set (0.00 sec)

mysql> create user world identified with mysql_native_password by 'パスワード';
mysql> grant all privileges on world to world@'%';
mysql> grant all privileges on `world`.city to 'world'@'%';
  • my.cnf修正
    default-authentication-pluginを追加
my.cnf
[mysqld]
default-authentication-plugin=mysql_native_password

※worldユーザ作成し、データにアクセスしようとしたら、以下のエラーが発生し、
SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client

ここここここを参考に色々やった結果、ユーザの作成コマンドや、my.cnfをいじって対応。

  • .envを修正
    DB_DATABASE, DB_USERNAME, DB_PASSWORDを修正する
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=world
DB_USERNAME=world
DB_PASSWORD=パスワード
  • WorldController修正
    use Illuminate\Support\Facades\DB; 追加
    index()を修正
use Illuminate\Support\Facades\DB;

    public function index()
    {
        $city = DB::select('select * from city');
        return view('world', ['city' => $city]);
        // return view('world');
    }
  • View修正
    cityテーブルのデータを表示する
<!doctype html>
<html>
  <body>
    <h1> Hello World </h1>
    <table border=1>
    <tr>
      <td>ID</td>
      <td>Name</td>
      <td>CountryCode</td>
      <td>District</td>
      <td>Population</td>
    </tr>
    <?php foreach($city as $row){ ?>
    <tr>
        <?php foreach($row as $cel){ ?>
            <td><?= $cel?></td>
        <?php } ?>
    </tr>
    <?php } ?>
    </table>
  </body>
</html>

MySQLに登録したデータが表示されればOK。

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