16.
查看購物車商品
- 修改路由
\專案\routes\web.php,在裡面加入一組購物車列表的設定(第8行),順便修改登入後,就直接執行ProductController@index,也就是顯示商品清單(第12行)
Route::pattern('id', '[0-9]+');
Route::get('/', 'ProductController@index')->name('index');
Route::get('/product', 'ProductController@index')->name('product.index');
Route::get('/product/{id}', 'ProductController@show')->name('product.show');
Route::post('/cart/store', 'CartController@store')->name('cart.store');
Route::get('/cart', 'CartController@index')->name('cart.index');
Auth::routes();
Route::get('/home', 'ProductController@index')->name('home');
- 修改控制器
\專案\app\Http\Controllers\CartController.php
public function index(Request $request)
{
$carts = $request->user()->carts()->get();
return view('cart.index', compact('carts'));
}
- 目前登入使用者是
$request->user(),因為我們有設模型關聯,所以,可以輕鬆抓出目前登入者的所有購物車資料,即$request->user()->carts()最後利用get()去抓取有資料出來即可。
- 記得要在index()中加入
Request $request,因為我們要利用$request->user()來抓取目前登入者的資訊。
- 接著建立新的視圖模板以顯示所有購物車內,先在
\專案\resources\views\底下建立cart目錄,然後建立\專案\resources\views\cart\index.blade.php,我們先做個形狀出來即可,真正的功能後續再加入:
@extends('layouts.app')
@section('content')
<h1>我的購物車</h1>
<table class="table table-striped">
<tr>
<th colspan=2>商品名稱</th>
<th nowrap class="text-right">商品單價</th>
<th nowrap class="text-center">購買數量</th>
<th nowrap class="text-right">小計</th>
<th>功能</th>
</tr>
@forelse($carts as $cart)
<tr>
<td>
<a target="_blank" href="/product/{{ $cart->product_id }}">
<img src="{{ $cart->product->image_url }}" class="img-thumbnail" style="width: 120px;">
</a>
</td>
<td>
<a target="_blank" href="/product/{{ $cart->product_id }}"><h5>{{ $cart->product->title }}</h5></a>
@if(!$cart->product->on_sale)
<div class="warning">该商品已下架</div>
@endif
</td>
<td class="text-right">{{ $cart->product->price }}</td>
<td class="text-center">{{ $cart->amount }}</td>
<td class="text-right">{{ $cart->product->price * $cart->amount }}</td>
<td nowrap><a href="#" class="btn btn-danger btn-sm">移除</a></td>
</tr>
@empty
<tr>
<td><h1>購物車空無一物</h1></td>
</tr>
@endforelse
</table>
@endsection
@section('scriptsAfterJs')
<script>
$(document).ready(function () {
});
</script>
@endsection
- ,為了翻變隨時可以觀看購物車,我們可以在選單的地方加入「我的購物車」連結,所以開啟
\專案\resources\views\layouts\nav.blade.php,在登入後的位置,加入一組連結:
<ul class="navbar-nav ml-auto">
<!-- Authentication Links -->
@guest
...略...
@else
<li class="nav-item">
<a class="nav-link" href="{{ route('cart.index') }}">我的購物車</a>
</li>
@section('my_menu')
@show
<li class="nav-item dropdown">
...略...
</li>
@endguest
</ul>
- 加入購物車之後直接跳轉至購物車清單,開啟
\專案\resources\views\product\add2cart.blade.php,我們在執行成功之後,用.then()來追加後續要執行的動作,並用location.href來完成轉址動作。
swal('加入購物車成功', '', 'success')
.then(function() {
location.href = '{{ route('cart.index') }}';
});