laravel で注文履歴を作成する機会があったのでアウトプットしていこうと思います。
仕様
①商品検索画面で商品を選択し、カートに入れます。
②カートに入れた商品を買いたい場合は確定ボタンを押します。
③確定した商品は注文履歴に表示されます。
画面
ER図
実装
▪️view
history.blade.php
<div class="container">
<div class="panel panel-default">
<h2><span class="panel-heading badge badge-secondary mt-3 mb-2">
//初期画面は全てのデータが表示されるようにしています。aタグを押下するたびに表示が切り替わります。
@foreach($idArray as $id)
@if($id === 'three')
<a href="{{route('order.all',['id'=>'all'])}}">全ての注文を表示</a>
@endif
@if($id === 'all')
<a href="{{route('order.all',['id'=>'three'])}}">直近3か月の注文を表示</a>
@endif
@endforeach
</span>
</h2>
<div class="panel-body">
</div>
<table class="table">
<thead>
<tr>
<th>No</th>
<th>注文番号</th>
<th>お届け先</th>
<th>備考</th>
<th></th>
</tr>
</thead>
<tbody>
//注文テーブルの情報を取り出してます。
@foreach($orders as $order)
<tr>
<td>{{$order->id}}</td>
<td>
//注文テーブルに紐づく、注文詳細テーブルの情報を取り出してます。
@foreach($order->orderDetails as $orderDetail)
@if ($loop->first)
{{$orderDetail->order_detail_number}}
@endif
@endforeach
</td>
<td>
//注文テーブルに紐づく、ユーザーテーブルの情報を取り出してます。
<p>〒{{$order->user->ZipcodeWithHyphen}}</p>
<p>
{{$order->user->prefecture}}
{{$order->user->municipality}}
{{$order->user->address}}
{{$order->user->apartments}}
</p>
<p>
{{$order->user->last_name}}
{{$order->user->first_name}}
様
</p>
</td>
<td>
<p>注文日時: {{$order->updated_at->format('Y/m/d')}}</p>
<p>注文状態:
@foreach($order->orderDetails as $key =>$orderDetail)
@if ($loop->first)
//注文詳細テーブルに紐づく発送状態テーブルの情報を取り出してます。
@if($orderDetail->shipmentStatus->shipment_status_name==='1')
発送前
@elseif($orderDetail->shipmentStatus->shipment_status_name==='2')
発送中
@else
発送済み
@endif
@endif
@endforeach
</p>
</td>
<td>
<a href="{{ route('order.details', ['order' => $order]) }}" type="submit" name="name" value="詳細" class="btn btn-primary">
詳細
</a>
</td>
</tr>
@endforeach
</tbody>
</table>
@if($orders->isEmpty())
注文履歴は存在しません
@endif
</div>
</div>
▪️controller
OrdersController.php
/**
* 注文履歴処理
*
*/
public function index($id)
{
//送られてきたパラメータ(id)に対して処理を分けています
$idArray = array('id' => $id);
$user=Auth::id();
if ($id === 'three') {
$carbon = new Carbon();
$now = $carbon->now();
$threeMonth = $carbon->subMonth(3);
$orders = Order::where('user_id', $user)
->whereBetween('updated_at', [$threeMonth, $now])
->with(['user', 'orderDetails.shipmentStatus'])//ユーザー情報と発送状況情報までデータ取得可能に
->orderBy('id', 'desc')
->paginate(15);
return view('order.history', ['orders' => $orders, 'idArray' => $idArray]);
} else {
$orders = Order::where('user_id', $user)
->with(['user', 'orderDetails.shipmentStatus'])
->orderBy('id', 'desc')
->paginate(15);
return view('order.history', ['orders' => $orders, 'idArray' => $idArray]);
}
}
▪️route
web.php
//1つのルーティングで全てデータ表示、直近3ヶ月のデータ表示に切り替わるようにしています。
Route::get('/orderHistory/{all}', 'OrdersController@index')->name('order.all');