LoginSignup
21
25

More than 5 years have passed since last update.

(超初心者向け)Laravel+Homesteadによるお小遣い帳サイト作成

Posted at

はじめに

  • Homestead上のLaravelでお小遣い帳サイトを作ります。
  • Laravelに手を付けてみたはいいもののどうしたら・・という人向けです。
  • 間違ってたら指摘して頂けると嬉しいです。主に自分向けのまとめです。
  • Homestead上へのLaravelのインストールまでは出来ている前提で進めます。
  • Laravelのバージョンは5.4.36です。

この記事でやること

  • HomesteadプリインのMySQLの設定確認
  • migrationによるテーブル作成
  • ControllerとViewの作成
  • ルーティング設定
  • formのsubmitボタン押下からのDBへのinsert
  • DBをControllerでクエリし、値をViewに渡す
  • bladeでのif文とforeach文
  • などなど

DBの設定

HomesteadではMySQLが最初からインストールされています。

$ vagrant ssh
Welcome to Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-92-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

3 packages can be updated.
0 updates are security updates.


Last login: Wed Nov 29 02:59:30 2017 from 10.0.2.2
vagrant@homestead:~$ mysql --version
mysql  Ver 14.14 Distrib 5.7.19, for Linux (x86_64) using  EditLine wrapper

MySQLのユーザー名、パスワードを知る方法

.env内に記述されています。laravelインストールディレクトリ(以下INSTALL_DIR)の直下にあります。
こんなん

.env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=*****************************
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=

テーブルの作成

テーブルはmigrationを使って作ります。
INSTALL_DIRをカレントディレクトリにしましょう。

$ php artisan make:migration create_hoge_table
Created Migration: 2017_12_06_045557_create_hoge_table

こうするとINSTALL_DIR/database/migrations/に2017_12_06_045557_create_hoge_table.phpが作られていると思います。

2017_12_06_045557_create_hoge_table.php
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateHogeTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
      Schema::create('saif', function(Blueprint $table) {
        $table->increments('saif_id');
        $table->string('saif_text');
        $table->integer('saif_money');
        $table->timestamps();
      });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('saif');
    }
}

upのところでテーブルを作成しています。
downはロールバック時に呼ばれます。

migrationの実行とエラーと対策

この時点ではまだDBにテーブルが作られていませんので、migrationを実行してテーブルを作成します。

$ php artisan migrate

すると

[Illuminate\Database\QueryException]                                                                                      
  SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = homestead a  
  nd table_name = migrations)

エラーになりました。
結論から言うとvagrant sshで入ってコマンド打てば解決です。

$ vagrant ssh
Welcome to Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-92-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

3 packages can be updated.
0 updates are security updates.


Last login: Wed Dec  6 05:11:24 2017 from 10.0.2.2
vagrant@homestead:~/code/laravel$ php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table
Migrating: 2017_12_06_045557_create_hoge_table
Migrated:  2017_12_06_045557_create_hoge_table

出来たので確かめてみましょう。

vagrant@homestead:~/code/laravel$ mysql -u homestead -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.7.19-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use homestead;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+---------------------+
| Tables_in_homestead |
+---------------------+
| migrations          |
| password_resets     |
| saif                |
| users               |
+---------------------+
4 rows in set (0.00 sec)

mysql> desc saif;
+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| saif_id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| saif_text  | varchar(255)     | NO   |     | NULL    |                |
| saif_money | int(11)          | NO   |     | NULL    |                |
| created_at | timestamp        | YES  |     | NULL    |                |
| updated_at | timestamp        | YES  |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

HTMLの作成

HTMLはちゃっちゃと作っちゃいましょう。が、ここで作るだけでは動作しません。(後でまた登場します)
ここではガワだけ作ります。ぶっちゃけ入力フォームがあれば何でもいいです。

※おこづかい帳なのに支出が無いじゃん!みたいなツッコミ無用w
 要は基本的な振る舞いを学べればいいのです。

後々の作業を楽にするために、INSTALL_DIR/resources/viewsにhoge.blade.phpを作ります。
同ディレクトリにwelcome.blede.phpがあることから分かる通り、ここがviewの置き場になります。

hoge.blade.php
<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Hoge</title>
    </head>
    <body>
      <div align="center"><center>
        <table border="0" width="640">
          <tr>
            <td colspan="2" width="100%">
              <font size="3">お小遣い帳</font><br>
            </td>
          </tr>
        </table>

        <br>
        <hr width = "640">
        <br>

        <table border="0" width="640">
          <tr>
            <td colspan="2" width="100%">
              <form action="" method="" name="hogeForm">
                <font size = "2">
                  入金額<br>
                  <input type="text" name="value" size="50" id="textfield1"><br>
                  <br>
                  内容<br>
                  <input type="text" name="text" size="50" id="textfield2"><br>
                  <br>
                  <input type="submit" value="実行" />
                </font>
              </form>
              <script type="text/javascript">
              document.getElementById('textfield1').focus();
              </script>
            </td>
          </tr>
        </table>

        <br>
        <hr width = "640">
        <br>
      </center></div>
    </body>
</html>

ControllerとViewの作成

DBにinsertしたり諸々するためのControllerを作ります。Modelも本当は必要なんだろうけど今回は省略しました。

以下のコマンドでControllerを作ります。
成功するとINSTALL_DIR/app/Http/Controllers/hoge/hogeController.phpが出来ます。

vagrant@homestead:~/code/laravel$ php artisan make:controller hoge/hogeController
Controller created successfully.

ルーティング設定

ルーティング設定をして、先ほど作ったHTMLをとりあえず出してみましょう。
INSTALL_DIR/routes/web.phpを触ります。

web.php
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Route::get('/hoge', 'hoge\hogeController@hoge');

こう書くと、homestead.app/hogeをブラウザでアクセスすると、hogeController.phpのhogeメソッドが呼ばれます。
先ほど書いたhogeController.phpをいじります。
以下のように書くとhoge.blade.phpが呼び出されます。

hogeController.php
<?php

namespace App\Http\Controllers\hoge;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class hogeController extends Controller
{
  public function hoge()
  {
      return view('hoge');
  }
}

これでHTMLを表示するところまで出来ました。

入力から反映まで

submitボタンを押してDBに値を書き込む

hoge.blade.phpとhogeController.phpをいじって、submitボタンが押されたら入力フォームの値をMySQLに書き込むようにします。

hoge.blade.php
<form action="/add" method="POST" name="hogeForm">
  <font size = "2">
  入金額<br>
  <input type="text" name="value" size="50" id="textfield1"><br>
  <br>
  内容<br>
  <input type="text" name="text" size="50" id="textfield2"><br>
  <br>
  <input type="submit" value="実行" />
  </font>
</form>

これでhomestead.app/addにPOST形式でリクエストが飛びます。
次にルーティング設定

web.php
Route::get('/hoge', 'hoge\hogeController@hoge');
Route::post('/add', 'hoge\hogeController@add');

筆者は上の行をコピペしてやっていたためにpostと書かないといけないところをgetで書いていてエラーが大量に出ました。
最後にController

hogeController.php
use Request;
use DB;

class hogeController extends Controller
{
  public function hoge()
  {
      return view('hoge');
  }

  public function add()
  {
      $value = Request::input('value');
      $text = Request::input('text');

      DB::insert('insert into saif (saif_text, saif_money) values (?, ?)', [$text, $value]);

      return view('hoge');
  }
}

これでsubmitボタンを押すとDBに値が書き込まれます。

DBの内容を画面に表示する

最後にDBの内容をクエリして画面に表示させます。
最初にControllerを触ります。

hogeController.php
public function hoge()
{
  $results = DB::select('select * from saif');
  return view('hoge')->with('results',$results);
}

これでhoge.blade.phpに値が渡ります。
hoge.blade.phpにはこんな感じで追記します。

hoge.blade.php
<table border="0" width="640">
  <tr>
    <td>内容</td>
    <td>金額</td>
  </tr>
  @if(isset ($results))
  @foreach($results as $result)
    <tr>
      <td>{{$result->saif_text}}</td>
      <td>{{$result->saif_money}}</td>
    </tr>
  @endforeach
  @endif
</table>

あ、そうそう/addでの表示時にもクエリした結果を表示させたいので以下のように変えます。

hogeController.php
public function add()
{
  $value = Request::input('value');
  $text = Request::input('text');

  DB::insert('insert into saif (saif_text, saif_money) values (?, ?)', [$text, $value]);

  return $this->hoge();
}

エラーと対策

Request::inputを呼ぶとエラーになる

use Illuminate\Http\Request;ではなくuse Request;を使うことで解決しました。

内容と金額が表示されず、コードがそのまま表示されてしまう

2重中括弧を忘れていませんか?これがないと出ません。

以上です

21
25
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
21
25