LoginSignup
0
2

More than 5 years have passed since last update.

[メモ]Laravel5.4でブログシステムを作る04(ルート、コントローラとデータベースの設定)

Last updated at Posted at 2017-10-05

ルートとコントローラの雛形

今回から実際にブログシステムを開発する。
第一回の文章モジュールの要件定義に沿ってルートをコントローラの雛形を作る。

まずは、コントローラをLaravelのコマンドラインで生成する。
文章モジュールに関する部分をPostとし、文章を扱っているコントローラをPostControllerにしよう。

$ php artisan make:controller PostController

コントローラを使用するには、Controllerクラスを継承することが必要

class PostController extends Controller
{
    // 文章リストを表示
    public function index(){}
    // 文章の詳細を表示
    public function show(){}
    //文章を作成
    public function create(){}
    //作った文章を保存、投稿
    public function store(){}
    //作った文章を編集
    public function edit(){}
    //文章を更新し、投稿
    public function update(){}
    //文章を削除
    public function delete(){}
}

続いて、routes/web.phpのルートを編集する。
ご注意:{}が含まれるものを後ろに置く。

// 文章リストを表示
Route::get('/posts','PostController@index');


//文章を作成 1.作成画面 
Route::get('/posts/create','PostController@create');
//文章を作成 2. 投稿
Route::post('/posts','PostController@store')

//文章を削除
Route::get('/posts/delete','PostController@delete');
//文章の詳細を表示
Route::get('/posts/{post}','PostController@show');
//作った文章を編集 1.画面 
Route::get('/posts/{post}/edit','PostController@edit');
//文章を作成 2. 更新を投稿
Route::put('/posts/{post}','PostController@update');

データベースの基本情報を設定

ルートディレクトリの直下で.envファイルを探す。使っているデータベースはmysqlで以下のように修正する:
各項目に実際のデータベースの設定を入れる。

DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=jianshu
DB_USERNAME=xxxxxx
DB_PASSWORD=xxxxxx

マイグレーションを使ってテーブルを生成

マイグレーションについて:

マイグレーションとはチームでアプリケーションデータベースのスキーマを更新し共有できるようなもので、
今回はまずマイグレーションを生成する。

$ php artisan migrate:install

実際のデータベースを調べたら、jianshuというデータベースの中にmigrationsのテーブルが生成したら、.envの設定が正しいと証明。

文章のテーブルの構成を考える:

description Field TYPE LENGTH
記事文章を記録するid id INT 10
記事文章のタイトル title VARCHAR 100
記事文章の内容、本文 content TEXT
記事文章の作者を記録するid user_id INT 11
文章が投稿された日時 create_at TIMESTAMP
文章が更新された日時 updated_at TIMESTAMP

表名をLaravelが推奨された通り、英文名+複数型とする。
モデルとテーブルの対応関係を考えた上で、モデル名はpostだとしたら、テーブル名をpostsとする。

次に、マイグレーションを使ってテーブルを生成する:

$ php artisan make:migration create_posts_table

database/migrationsディレクトリの中に生成日時+create_posts_table.phpが生成される。
このファイルに入って、CreatePostsTableのクラスに以下のようにメソッドを追加する。

  public function up()
    {
        //テーブルを作成
        Schema::create('posts',function(Blueprint $table){
            //idを自動的に増加
            $table->increments('id');
            $table->string('title',100)->default('');
            $table->text('content');
            $table->integer('user_id')->default(0);
            $table->timestamps();
        });


    }
    public function down()
    {
        //ロールバック
        Schema::dropIfExists('posts');
    }

テーブルを設定し終わったら、以下のように執行し、postsテーブルが生成される。

$ php artisan migrate

ロールバックする

$ php artisan migrate:rollback    
0
2
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
2