1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravelで「SOLD」表示を実装する方法(購入済み判定)

Posted at

🎯 やりたいこと

LaravelでEC風アプリを作る中で、「すでに購入された商品にはSOLDラベルを表示」という機能を実装しました。

🧩 前提

  • Laravel 10
  • Bladeテンプレート使用
  • 購入情報は purchases テーブルに保存(1商品=1購入の前提)

✅ 実装の流れ

  1. モデルにリレーションを追加
  2. コントローラーでリレーションを読み込む
  3. Bladeで条件分岐してラベル表示
  4. CSSで目立たせる

🧠 モデルの設定

// Item.php
public function purchase()
{
    return $this->hasOne(Purchase::class);
}

✅ 実装の流れ

  1. 購入済みかどうかを判定するフラグを ItemController@show に追加
  2. Bladeで条件分岐して「SOLD」ラベルを表示
  3. CSSで目立たせる

🧠 コントローラー側

// ItemController.php
public function show($id)
{
    $item = Item::with('purchase')->findOrFail($id);
    return view('items.show', compact('item'));
}

🖥 Bladeの表示部分

@if ($item->purchase)
    <span class="sold-label">SOLD</span>
@endif

🎨 CSS(例)

.sold-label {
    background-color: red;
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-weight: bold;
}

1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?