<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateItemsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('items', function (Blueprint $table) {
$table->id();
$table->string('name', 50);
$table->integer('price');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('items');
}
}
ソート条件を書く
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Item;
class ItemController extends Controller
{
public function index(Request $request)
{
// セレクトボックスで選択した値
$select = $request->price;
// セレクトボックスの値に応じてソート
switch ($select) {
case '1':
//「指定なし」はID順
$items = Item::get();
break;
case '2':
// 「価格が低い順」でソート
$items = Item::orderBy('price', 'asc')->get();
break;
case '3':
// 「価格が高い順」でソート
$items = Item::orderBy('price', 'desc')->get();
break;
default :
// デフォルトはID順
$items = Item::get();
break;
}
return view('item.index', compact('items', 'select'));
}
}
コメント