我在视图页面上添加了一个按钮,但当我单击它时,它应该显示在同一页面上,但显示的结果将转到其他页面。以下是视图文件的代码:
<a href="{{url('/cart/add')}}/{{$p->id}}" class="button add-cart-cat button--small card-figcaption-button">Add to Cart</a>
控制器文件为:
public function addItem($id){
$pro = products::find($id);
Cart::add(['id' => $pro->id, 'name' => $pro->pro_name,
'qty' => 1, 'price' => $pro->pro_price,
'options' =>[
'img' => $pro->pro_img
]]);
echo "add to cart successfully";
}
在上面的控制器中,我提到过会传递值,然后显示成功的消息,是的,它确实显示了结果,但在其他空白页上
顺便说一句,这是我使用的路由文件以及
Route::get('cart/add/{id}', 'cartController@addItem');
那么,当我点击按钮时,有什么方法可以在同一页面上显示结果吗?谢谢
请参阅相关文档。
问题是,你要发布到/cart/add
,然后你应该将用户重定向回页面,但你没有。。。相反,您只是在/cart/add
页面上回显一个响应。
相反,做这个
public function addItem($id){
$pro = products::find($id);
Cart::add(['id' => $pro->id, 'name' => $pro->pro_name,
'qty' => 1, 'price' => $pro->pro_price,
'options' =>[
'img' => $pro->pro_img
]]);
//echo "add to cart successfully";
//Return the user back to the page they came from with a message
return back()->with('status', 'add to cart successfully');
}
然后在您的页面刀片文件中添加到购物车按钮所在的位置,将其添加到某个位置。。。
//If the session has a message to display, then show it
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
如果您不使用Bootstrap,那么可以根据您的意愿自定义消息html/css。
您没有重定向页面
你应该用你的消息重定向路由。
示例
public function addItem($id){
$pro = products::find($id);
Cart::add([
'id' => $pro->id, 'name' => $pro->pro_name,
'qty' => 1, 'price' => $pro->pro_price,
'options' =>[
'img' => $pro->pro_img
]
]);
Session::flash('message', "add to cart successfully");
return Redirect::back();
}
注意:在namespace
之后,您必须将use Session;
放在控制器的顶部
然后你可以在刀片中接收到所有的闪光信息,如下所示:
@if (Session::has('message'))
<div class="alert alert-info">{{ Session::get('message') }}</div>
@endif