0
0

More than 1 year has passed since last update.

Laravel8(API) × Vue.js で中間テーブルにPOSTする

Posted at

現在お知らせ機能を実装しており、「次回から表示しない」ボタンを配置しています。ユーザーごとにどのお知らせを非表示にするかを管理するために、中間テーブルを作成しています。
現状はINSERTで中間テーブルにレコードを追加しています。
Vue.jsでaxiosを使って、APIからお知らせの情報を取得&表示まで実装済。
今回はAPIを完成することをゴールとします。

Laravel8(APIモード)
Vue2(SPA)

実装手順

  • 中間テーブルのモデルを作成&関連付け
  • UserControllerで中間テーブルへPOSTする内容を記述
  • ルーティングの設定(api.php)
  • PostmanでPOSTリクエスト送信
  • Vue.jsからのリクエスト→APIとの疎通を確認

中間テーブルのモデルを作成&関連付け

多対多の中間(ピボット)テーブルのモデルを作成する場合、usingメソッドを呼び出すこと。
Notificationsモデル

public function users() {
        return $this->belongsToMany(User::class)->withPivot(['read', 'hide_next'])->using(NotificationUser::class);
    }

Usersモデル

public function notifications() {
        return $this->belongsToMany(Noification::class)->withPivot(['read', 'hide_next'])->using(NotificationUser::class);
    }

ピボットテーブル用モデル生成

php artisan make:model NotificationUser

NotificationUserモデル

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;

class NotificationUser extends Model
{
    use HasFactory;

    protected $fillable = ['id','notification_id','user_id','read','hide_next','created_at','updated_at'];
}

ちなみに、モデルを作成した際は、

protected $fillable = ['hoge'];
0
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
0
0