LoginSignup
45
42

More than 5 years have passed since last update.

Laravel+Reactのチュートリアル

Last updated at Posted at 2016-07-18

環境

  • Laravel 5.2-5.3
  • React 15.2.1

Laravel Elixirを使ってES2015で書いていく想定。

準備

laravel new laravel-react-tutorial
cd laravel-react-tutorial

Laravel5.2ではElixir5.0だけどもうすぐリリース予定の5.3では6.0を使ってるので6.0に変更。

package.json
{
  "private": true,
  "scripts": {
    "prod": "gulp --production",
    "dev": "gulp watch"
  },
  "devDependencies": {
    "gulp": "^3.9.1",
    "laravel-elixir": "^6.0.0-9",
    "laravel-elixir-webpack-official": "^1.0.2",
    "bootstrap-sass": "^3.3.0"
  }
}
npm i

Reactに必要なものはほとんど揃ってるので追加するのはreactだけでいいはず。

npm i react react-dom -D

Laravel5.3のgulpfile.jsはwebpack使うのがデフォルト。

gulpfile.js
var elixir = require('laravel-elixir');

elixir(function (mix) {
    mix.sass('app.scss')
       .webpack('app.js');
});

ここまででビルドはできるようになってる。
resources/assets/js/app.jsを変更。

app.js
import React from 'react';
npm run prod

public/js/app.jsがビルドされていればここまでは準備完了。
Laravel5.3ならpackage.jsonとgulpfile.jsの変更は不要だからほとんど準備なしで使える。
Elixirが楽すぎてLaravel関係ないJSだけの時でもElixir使ったりする…。

おまけでバージョン付け。

gulpfile.js
elixir(function (mix) {
    mix.sass('app.scss')
        .webpack('app.js')
        .version([
            'css/app.css',
            'js/app.js'
        ]);
});

Hello, World!

次はここのHello World
https://facebook.github.io/react/docs/package-management.html

app.js
import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
    <h1>Hello, world!</h1>,
    document.getElementById('example')
);

npm run prodでビルドを忘れないように。
(この辺うっかり忘れやすいのでビルドしたものをgitに含めるか、デプロイの度にビルドするかどうかは議論されるけどまぁ各自の好みで)

表示するhtmlはLaravelデフォルトのresources/views/welcome.blade.phpを変更。
適当な所に追加。

<div id="example"></div>

<script src="{{ elixir('js/app.js') }}"></script>

サーバーはとりあえずphp artisan serve
上手くHello, World!が表示されていれば成功。

test

なお、Laravel側からのテストでこういうことやっても当然成功しない。

  $this->visit('/')
       ->see('Hello, World!');

ReactのテストはReact側で。
今はスルーしておく。

Homestead

こんなHello Worldレベルじゃ動かすだけで終わるのでもう少し続く。
普段はartisan serve使わないのでいつもの開発環境になるようにHomesteadで動かす。

チュートリアルらしいことはここまでになりそう。

コメントボックス

次はこのチュートリアル
https://facebook.github.io/react/docs/tutorial-ja-JP.html

サーバーサイドから

こっちのほうが簡単なのでAPI用意しておく。

php artisan make:model Model/Comment -m

migration

    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->string('author');
            $table->string('text');
            $table->timestamps();
        });
    }

Commentモデルのfillable

    protected $fillable = [
        'author',
        'text',
    ];

migrate

php artisan migrate

seeder。DatabaseSeeder.php。いつもはseeder使わないけど。

   Comment::create([
            'author' => 'Pete Hunt',
            'text' => 'Hey there!'
        ]);

   Comment::create([
            'author' => 'Paul O’Shannessy',
            'text' => 'React is *great*!'
        ]);
php artisan db:seed

CommentController

php artisan make:controller CommentController --resource
    public function index()
    {
        $comment = Comment::latest('created_at')->take(10)->get();

        return $comment;
    }

HomeController

php artisan make:controller HomeController
    public function index()
    {
        return view('commentbox');
    }

resources/views/commentbox.blade.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8"/>
  <title>React Tutorial</title>
</head>
<body>
<div id="content"></div>

<script src="{{ elixir('js/app.js') }}"></script>

</body>
</html>

routes.php

Route::group(['prefix' => 'api'], function () {
    Route::resource('comments', 'CommentController');
});

Route::get('/', 'HomeController@index');

/でチュートリアルのindex.html。
/api/commentsでコメントのjson。
まぁいつもやってることの簡易版。

やっとReactだけど

ES2015版チュートリアルなだけなので他の記事と同じ。省略で良さそう。
これとか
http://qiita.com/nownabe/items/2d8b92d95186c3941de0
ただし1年前の記事でもすでに若干古くなってたりするので公式情報を一番参考に。

ReactとReactDOMに分かれてたり…。

ES2015を使わないなら公式のままできる。
上手く動かない時とかは全部消してES5で書けばいい。
.jsはどっちで書いてもいいように変換してくれる。

感想

今時はどんな新しいことでもすぐに調べて覚えられるけどそれが本当に効率いいかはよく考えて判断する。

45
42
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
45
42