スコープの使い方 [Laravel]
Laravelの「スコープ」はモデルに独自機能を付与するものです。
使い方
モデル
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Question extends Model { public function scopeIDGreaterThan($query, $id) { return $query->where('id','>=', $id); } public function scopeIDLessThan($query, $id) { return $query->where('id', '<=', $id); } }
コントローラー
モデルのスコープを呼び出すときは「scope」を外します。
use App\Question; // 1つのスコープを使う $items = Question::IDGreaterThan(3)->get(); return view('index', ['items' => $items]); // 2つのスコープを使う $items = Question::IDGreaterThan(3)->IDLessThan(5)->get(); return view('index', ['items' => $items]);
ビュー
@foreach ($items as $item) <p>{{ $item->title }}</p> @endforeach
スポンサーリンク
関連記事
公開日:2020年11月17日
記事NO:02853