1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

(メモ) paiza.cloudでlaravelの入門してみた

Last updated at Posted at 2018-08-17

アカウント作成

  • https://paiza.cloud/
  • Githubのアカウントで作れる。
  • Laravel, mysql, Apacheをクリックしてちょっと待てば作成できる。

以下はpaiza関係ない。ローカル環境で実施しました。

Laravelアプリケーションの作成

composer
# composerのインストール
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
chmod +x 
composer --version

# composerを最新版に
# composer self-update


# インストールを早めるため1
composer config -g repositories.packagist composer 'https://packagist.jp'

# インストールを早めるため2
sudo apt install -y php-curl
composer global require hirak/prestissimo
laravel
# laravelのインストール
sudo apt install -y php-zip
composer global require "laravel/installer"

# PATHの追加
export PATH=$PATH:~/.config/composer/vendor/bin/
プロジェクトの準備
# カレントディレクトリにインストール
sudo apt install -y php-mbstring php-xml
laravel new myapp

# プロジェクトのコメント部分を日本語化
composer global require laravel-ja/comja5:~1
cd myapp
comja5 -a

# git
git init
git add -A
git commit -m init

動作確認

php artisan serve

編集

  • resources/views/welcome.blade.php を編集してみる。
resources/views/welcome.blade.php
 81                 <div class="title m-b-md">
 82                     Laravel編集してみた
 83                 </div>

mysql

sudo apt install -y mysql-server

# mysql接続。-pは適宜変える
mysql -uroot -proot

create database mydb;

modelの準備

.env
DB_DATABASE=mydb
DB_USERNAME=root
DB_PASSWORD=secret
php artisan make:model Task -m -c -r

modelの編集

  • database/migrations/2018_08_*_create_tasks_table.php
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->increments('id');
+           $table->string('name');
            $table->timestamps();
        });
    }
sudo apt install -y php-mysql
php artisan migrate

# テーブルを削除して作り直す場合は以下
# php artisan migrate:refresh

確認

mysql -uroot -proot mydb
nameカラムが追加されていることを確認
mysql> desc tasks;
+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255)     | NO   |     | NULL    |                |
| created_at | timestamp        | YES  |     | NULL    |                |
| updated_at | timestamp        | YES  |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+

ルーティングの編集

routes/web.php
# トップページにアクセスしたら `/tasks` に飛ぶ
Route::get('/', function(){return redirect('/tasks');});

# /tasksにGETで index
Route::get('/tasks', 'TaskController@index');

# /tasksにPOSTで store
Route::post('/tasks', 'TaskController@store');

# /tasksにDELETEで destroy
Route::delete('/tasks/{id}', 'TaskController@destroy');

# 強制的にhttps通信
\URL::forceScheme('https');

Taskコントローラを編集してみる

app/Http/Controllers/TaskController.php
  namespace App\Http\Controllers;
  
  use App\Task;
  use Illuminate\Http\Request;
  
  class TaskController extends Controller
  {
      public function index()
      {
+         $tasks = Task::all();
+         return view('tasks', ['tasks' => $tasks]);
      }
  (略)
      public function store(Request $request)
      {
+         $task = new Task;
+         
+         $task->name = request('name');
+         $task->save();
+         return redirect('/tasks');
      }
  (略)
-     public function destroy(Request $request)
+     public function destroy(Request $request, $id)
      {
+         $task = Task::find($id);
+         $task->delete();
+         return redirect('/tasks'); 
      }
  }

共通ファイル:layout

  • resources/views/layout.blade.php
<!DOCTYPE html>
<html>
    <head>
        <title>Task List</title>
        <!-- CSS And JavaScript -->
        <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic">
        <link rel="stylesheet" href="//cdn.rawgit.com/necolas/normalize.css/master/normalize.css">
        <link rel="stylesheet" href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    </head>
    <body>
        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

taskビュー

  • resources/views/tasks.blade.php
@extends('layout')

@section('content')
    <h1>Task List</h1>
    <form action="/tasks" method="POST" class="form-horizontal">
        {{ csrf_field() }}
        <!-- Task Name -->
        <div class="form-group">
            <label for="task" class="col-sm-3 control-label">Task</label>
            <div class="col-sm-6">
                <input type="text" name="name" id="task-name" class="form-control" required>
            </div>
        </div>

        <!-- Add Task Button -->
        <div class="form-group">
            <div class="col-sm-offset-3 col-sm-6">
                <button type="submit" class="btn btn-default">
                    <i class="fa fa-plus"></i> Add Task
                </button>
            </div>
        </div>
    </form>

    <!-- Current Tasks -->
    <h2>Current Tasks</h2>
    <table class="table table-striped task-table">
        <thead>
            <th>Task</th><th>&nbsp;</th>
        </thead>

        <tbody>
            @foreach ($tasks as $task)
                <tr>
                    <!-- Task Name -->
                    <td>
                        <div>{{ $task->name }}</div>
                    </td>
                    <td>
                        <form action="/tasks/{{ $task->id }}" method="POST">
                            {{ csrf_field() }}
                            {{ method_field('DELETE') }}                    
                            <button>Delete Task</button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>
@endsection

mm.png

メール送信

php artisan make:mail ContactSent
class ContactSent extends Mailable
{
 (略)
-   public function __construct()
+   public function __construct($name)
    {
+        $this->name = $name;
    }

    public function build()
    {
+        return $this
+           ->from('送信元のアドレス')
+           ->subject('テスト送信完了'.$this->name)
+           ->view('emails.tasks');
    }
}
  • emails.tasks は、resources/views/emails/tasks.blade.phpを指す。
resources/views/emails/tasks.blade.php
本文です
.env
MAIL_DRIVER=smtp
MAIL_HOST=どこかのリレーサーバー
MAIL_PORT=25
app/Http/Controllers/TaskController.php
    public function store(Request $request)
    {
        //
        $task = new Task;

        $task->name = request('name');
        $task->save();

+       \Mail::to("送信先のアドレス")
+               ->send(new ContactSent($task->name));

        return redirect('/tasks');
    }
  • これで「追加」ボタンを押すたびにメールが届く

.envの値がうまく反映されていない時すること

  • メールの設定でハマっていた。調べてみたところ、ddという命令が使える様子。
dd(\Config::get('mail'));

mmm.png

これで治る
php artisan config:cache
1
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?