LoginSignup
2
0

More than 3 years have passed since last update.

EC2のLaravel6.0環境でリレーションさせる AWS/Laravel連載(12)

Last updated at Posted at 2019-10-16

はじめに

前回の記事でLaravel+Vueを使い、API経由で新規投稿を実装しました。

EC2のLaravel6.0環境でVue+Rest APIを連携する AWS/Laravel連載(11)

今回は投稿をユーザーIDに紐付けて、その投稿をどのユーザーがしたものかデータを紐付けます。

migrationファイルを作る

$ php artisan make:migration add_user_id_to_posts_table --table=posts
database/migrations/xxxx_xx_xx_xxxxxx_add_user_id_to_posts_table.php
...
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            //
            $table->bigInteger('user_id')->unsigned();

            $table->foreign('user_id')
                  ->references('id')->on('users')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            //
            $table->dropForeign('posts_user_id_foreign');

            $table->dropColumn('user_id');
        });
    }
...

user_idというカラムを作って、usersテーブルの外部キーにします。

downのdropForeignの書き方が特殊なので要注意!
いざという時にmigrate:resetが効かなくならないよう、必ずdownの挙動も確認しましょう。

$ php artisan migrate

これでカラム追加ができました。

Laravel上で関連付ける

app/User.php
...
    /**
     * 投稿取得
     */
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
...

これにより、コントローラー等でuserインスタンスからそのユーザーの投稿が取得できます。

$user->posts()->first()->content; // そのユーザーが投稿した1件目のデータの本文を表示
app/Post.php
...
    /**
     * ユーザーを取得
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
...

これにより、postインスタンスからユーザー情報が取得できます。

$post->user->name; // 投稿したユーザー名を表示

投稿保存処理でユーザー情報を紐付ける

本来は認証済みユーザーに紐付いた投稿にさせたいのですが、API化しているのでAPIで認証情報を取得する必要があります。
この方法は次回記事で紹介するので、今回はダミーでid:1のユーザーの投稿としてみなします。

app/Http/Controllers/PostController.php
...
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'title' => 'required|max:255',
            'content' => 'required',
        ]);
        $user = \App\User::find(1); // ここ次回記事で直します。暫定的にid:1のユーザー投稿とみなす
        return $user->posts()->create($request->all());
    }
...
2
0
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
2
0