LoginSignup
0
0

More than 3 years have passed since last update.

laravelでsqliteで接続していたDBをmysqlに切り替える方法

Last updated at Posted at 2020-01-11

前提条件

mysql -u rootで接続
テーブルはpostsテーブルを使用(id.titleのみの構造)
モデルはPost.php

mysql> desc posts;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  |     | NULL    |       |
| title | varchar(10) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
mysql> select *from posts;
+------+--------+
| id   | title  |
+------+--------+
|    1 | Yamada |
+------+--------+
index.blade.php


  @forelse ($posts as $post)

  <tbody>
    <tr>

      <th scope="row">1</th>
      <td>  <a href="{{ action('PostsController@show', $post) }}">{{ $post->title }}</a>
</td>
      <td> <a href="{{ action('PostsController@edit', $post) }}" class="edit">[Edit]</a>
</td>

      <td> <a href="#" class="del" data-id="{{ $post->id }}">[x]</a>
      <form method="post" action="{{ url('/posts', $post->id) }}" id="form_{{ $post->id }}">
      {{ csrf_field() }}
      {{ method_field('delete') }}
    </form>
</td>

    </tr>
    @empty
@endforelse

Postscontroller

indexアクション
 public function index() { 
     $posts = Post::all(); 
     return view('posts.index', ['posts' => $posts]);
      }

.env

.env変更後は$ php artisan config:cache実行

sqlite接続時

DB_CONNECTION=sqlite

#DB_CONNECTION=mysql
#DB_HOST=127.0.0.1 
#DB_PORT=3306
#DB_DATABASE=myblog
#DB_USERNAME=root
#DB_PASSWORD=
mysql接続時 


#DB_CONNECTION=sqlite

DB_CONNECTION=mysql
DB_HOST=127.0.0.1  
DB_PORT=3306
DB_DATABASE=DB名
DB_USERNAME=root
DB_PASSWORD=

database.phpは特に触らず

config/database


  'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'myblog'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

表示されました!

スクリーンショット 2020-01-11 20.04.55.png

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