Macのローカルにlaravel 5.6のインストール | アプリ開発のおぼえがき2

Model作成がおわったので、次はControllerを作成する

コントローラー生成

artisanコマンドでコントローラーを作成する

$ php artisan make:controller ArticlesController -r
Controller created successfully.

すると
app/Http/Controllers/ArticlesController.php
が生成されてる

中身をチェックすると

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ArticlesController 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)
    {
        //
    }
}

こんな感じ
各種定義されている関数を調べようと思ったけどまだ時間がかかりそうだから次に進む。


ルーティングの設定をする

色々調べるとリソースフル(Resourceful)というワードをよく見る

よくわからなかったが、下記の記事がわかりやすかった。
https://qiita.com/michiomochi@github/items/de19c560bc1dc19d698c

知らないままやっていたけど
artisan make:Controllerのところでつけていた-rオプションは、「Resourcefulなアクションを自動で定義したコントローラーを生成する」というものらしい

よくわからないけど、ルーティングの設定の際にリソースフルなルーティング設定を行う必要があるとのこと

ルーティングの設定はroutesディレクトリ配下のファイルにて設定する模様

見てみると
api.php
channels.php
console.php
web.php
があり、ここでゴニョゴニョするっぽい

主にapi.phpとweb.phpで、各ファイルの用途は

WEBサイトアプリケーションのルーティングをしたい → web.php
APIとしてのルーティングをしたい → api.php

らしい。
なんともわかりやすい名前。

今回はAPIは作らずにWEBアプリを作りたいため、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');
});

中身はこんなかんじ。

今回作成したArticlesControllerに対してルーティングを設定したいので、

Route::resource('articles', 'ArticlesController');

を追記

設定したものが正しく動作しているかどうかをチェックするには

$ php artisan route:list

artisanにてリスト表示することが可能な模様

試しに出してみると

$ php artisan route:list
+--------+-----------+-------------------------+------------------+-------------------------------------------------+--------------+
| Domain | Method    | URI                     | Name             | Action                                          | Middleware   |
+--------+-----------+-------------------------+------------------+-------------------------------------------------+--------------+
|        | GET|HEAD  | /                       |                  | Closure                                         | web          |
|        | GET|HEAD  | api/user                |                  | Closure                                         | api,auth:api |
|        | GET|HEAD  | articles                | articles.index   | App\Http\Controllers\ArticlesController@index   | web          |
|        | POST      | articles                | articles.store   | App\Http\Controllers\ArticlesController@store   | web          |
|        | GET|HEAD  | articles/create         | articles.create  | App\Http\Controllers\ArticlesController@create  | web          |
|        | GET|HEAD  | articles/{article}      | articles.show    | App\Http\Controllers\ArticlesController@show    | web          |
|        | PUT|PATCH | articles/{article}      | articles.update  | App\Http\Controllers\ArticlesController@update  | web          |
|        | DELETE    | articles/{article}      | articles.destroy | App\Http\Controllers\ArticlesController@destroy | web          |
|        | GET|HEAD  | articles/{article}/edit | articles.edit    | App\Http\Controllers\ArticlesController@edit    | web          |
+--------+-----------+-------------------------+------------------+-------------------------------------------------+--------------+

こんな感じ。
気になったのはmake:Controllerで作成して自動的に記述されていたindex, store, create, show....といった関数が自動的に認識されていて、それぞれに対してMethodが変わっているということが気になった。

おそらく定義する方法によってこの箇所が変わってくるのかなと思ったが一旦放置

試しにアクセスしてみたけどもちろんviewも何も作ってないので真っ白だった。
http://127.0.0.1:8000/articles

表示確認がしたい

モデル、コントローラー、ルーティングが完了したので、あとはデータを入れるのとViewの用意をする

まずデータは、前回作ったArticleModelにダミーデータを作る

seederというものがあるらしい(artisanなんでもあるのな)

コードはこんなかんじ

// seederファイルを作成する
$ php artisan make:seeder ArticlesTableSeeder
Seeder created successfully.

これを実行すると、database/seeds/にArticleTableSeeder.phpが出来上がった。

<?php

use Illuminate\Database\Seeder;

class ArticlesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //
    }
}

中身はこんなかんじ

runの中にダミーデータ挿入のためのプログラムを追記

    public function run()
    {
        DB::table('articles')->insert([
            [
            'title' => 'タイトル1',
            'body' => '内容1'
            ],
            [
            'title' => 'タイトル2',
            'body' => '内容2'
            ],
            [
            'title' => 'タイトル3',
            'body' => '内容3'
            ],
        ]);
    }

うーん、なんとも直感的な書き方。

これを保存したら、実際にseederを実行するために、database/seeds/DatabaseSeeder.phpに実行のための文を追記するらしい

DatabaseSeeder.phpの中身はこんなかんじ

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
    }
}

$this->call(UsersTabelsSeeder::class);とあるので、作ったseederファイルを指定すればいいっぽい

    public function run()
    {
        $this->call(ArticlesTableSeeder::class);
    }

に変更。

あとはartisanで

$ php artisan db:seed

結果が何も出なかったからDBに入ってるか確認

と、何故かここでmysqlがぶっ壊れる

ナンデェッェエェェェェ

ERROR! MySQL server PID file could not be found!

うう、、、
解決する時間が惜しいのでもうマシンを変えます。

情報は一杯あるようなので大丈夫かな


長くなりそうなので一旦締めまっす

つづきは3へれっつごー



この記事が気に入ったらサポートをしてみませんか?