I am creating website using laravel 5.1. I have used the built in user authentication system. In my application I'm trying to add an item to my shopping cart and have set this route to use the auth middleware. Everything works when the user is already logged in but throws MethodNotAllowedHttpException when the user is not already logged in.
I have registered the route in routes.php like this :
Route::post('addtocart',['middleware'=>'auth','as'=>'addtocart','uses'=>'PurchaseController@postaddtoCart']);
HTML form: Here $url=route('addtocart');
<form method ="POST" action = {{$url}}>
{!! csrf_field() !!}
<ul class="product-qty">
<span>Quantity:</span>
<input name="qty" type="number" min=100 max=1000 required>{{$res->unit_of_measurement}}</input>
</ul>
<div class="btn_form button item_add item_1">
<input type="submit" value="Add to Cart" title="" {{$btnstatus}}>
<label>{{$labelstat}}</label>
<input name="prodcode" readonly hidden value={{$res->product_code}} ></input>
<input name="db" readonly hidden value={{$dbname}} ></input>
</form>
Method in the Controller:
public function postaddtoCart(Request $request)
{
$dbname=$request->input('db');
$qty=$request->input('qty');
$product_code=$request->input('prodcode');
$cats=DB::connection('mysql1')->select("select criteria from ".$dbname.".classification");
$res =DB::connection('mysql1')->select("select * from ".$dbname.".products where product_code='".$product_code."'");
$imgs=DB::connection('mysql1')->select("select image from ".$dbname.".images where product_code='".$product_code."'");
$cart = Cart::find(Auth::user()->CustomerId);
if(is_null($cart))
{
$cart=new Cart;
$cart->cartId=Auth::user()->CustomerId;
$cart->save();
}
if(!(DB::table('Cartdetails')->where('cartId',Auth::user()->CustomerId)->where('product_code',$product_code)->first()))
{
DB::table('Cartdetails')->insert(
['cartId' => Auth::user()->CustomerId, 'product_code'=>$product_code,'unit_of_measurement'=>$res[0]->unit_of_measurement,
'cost_per_unit'=>$res[0]->Price,
'quantity'=>$qty,
'Total_cost'=>($qty*$res[0]->Price),
'database'=>$dbname]);
$ucart = Cart::find(Auth::user()->CustomerId);
$ucart->Total_cost = $ucart->Total_cost + ($qty*$res[0]->Price);
$ucart->save();
}
return redirect('/cart');
}
Changing 'post' to 'any' in routes.php removes the MethodNotAllowedHttpException but then it seems that the request is empty. All the $request->input() lines in the controller return empty results. How can i solve this issue ?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire