laravel-5.8:The POST method is not supported for this route. Supported methods: GET, HEAD - laravel

hi m trying to add products in cart but it says: The POST method is not supported for this route. Supported methods: GET, HEAD.. (View: \resources\views\product\detail.blade.php), I wants that by clicking the addtocart it redirect me to that age with products,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,...…………………………………..,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
route:
Route::get('cart', 'Admin\ProductController#cart')->name('product.cart');
Route::get('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
controller:
public function cart()
{
if (!Session::has('cart')) {
return view('products.cart');
}
$cart = Session::has('cart');
return view('product.cart', compact('cart'));
}
public function addToCart(Product $product, Request $request)
{
if(empty(Auth::user()->email)){
$data['email'] = '';
}else{
$data['email'] = Auth::user()->email;
}
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$qty = $request->qty ? $request->qty : 1;
$cart = new Cart($oldCart);
$cart->addProduct($product);
Session::put('cart', $cart);
return redirect()->back()->with('flash_message_success', 'Product $product->title has been successfully added to Cart');
}
view:
<form method="POST" action="{{ route('addToCart') }}" enctype="multipart/form-data">
<div class="btn-addcart-product-detail size9 trans-0-4 m-t-10 m-b-10">
#if($product->product_status == 1)
<!-- Button -->
<button class="flex-c-m sizefull bg1 bo-rad-23 hov1 s-text1 trans-0-4">
Add to Cart
</button>
#else Out Of Stock #endif
</div>
</form>
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cart
{
private $contents;
private $totalQty;
private $contentsPrice;
public function __construct($oldCart){
if ($oldCart) {
$this->contents = $oldCart->contents;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function addProduct($product, $qty){
$products = ['qty' => 0, 'price' => $product->price, 'product' => $product];
if ($this->contents) {
if (array_key_exists($product->slug, $this->contents)) {
$product = $this->contents[$product->slug];
}
}
$products['qty'] +=$qty;
$products['price'] +=$product->price * $product['qty'];
$this->contents[$product->slug] = $product;
$this->totalQty+=$qty;
$this->totalPrice += $product->price;
}
public function getContents()
{
return $this->contents;
}
public function getTotalQty()
{
return $this->totalQty;
}
public function getTotalPrice()
{
return $this->totalPrice;
}
}

First of all your form method in the view is POST but you don't have a post route.
Second, the route that you have defined expect a parameter(product) you can change the form action as below BUT I think you want to send the user to another page so you can use a link instead of form.
Here's the form action:
action="{{ route('addToCart', $product->id) }}"
And if you want to use link, you can do something like this:
.....

Your method should be POST. In the form, you're calling it Post method but in route.php file, you defined as get to change it as Route::post
Route::post('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
In addition, your route.php file expecting {product} so you need to pass it in form route so your action be like {{ route('addToCart',$product->id) }}
<form method="POST" action="{{ route('addToCart',$product->id) }}" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

Related

404 on add to cart laravel

i have this situation on add to cart when i want to add to cart i am getting 404 error,
this is my route
Route::get('/add-to-cart/{product}', [CartController::class, 'addToCart'])->name('add.cart');
Route::get('/remove/{id}', [CartController::class, 'removeFromCart'])->name('remove.cart');
Route::get('/change-qty/{product}', [CartController::class, 'changeQty'])->name('change_qty');
This is controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Products;
class CartController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
return view('cart.index');
}
public function addToCart(Products $product)
{
$cart = session()->get('cart');
if (!$cart) {
$cart = [$product->id => $this->sessionData($product)];
return $this->setSessionAndReturnResponse($cart);
}
if (isset($cart[$product->id])) {
$cart[$product->id]['quantity']++;
return $this->setSessionAndReturnResponse($cart);
}
$cart[$product->id] = $this->sessionData($product);
return $this->setSessionAndReturnResponse($cart);
}
public function changeQty(Request $request, Products $product)
{
$cart = session()->get('cart');
if ($request->change_to === 'down') {
if (isset($cart[$product->id])) {
if ($cart[$product->id]['quantity'] > 1) {
$cart[$product->id]['quantity']--;
return $this->setSessionAndReturnResponse($cart);
} else {
return $this->removeFromCart($product->id);
}
}
} else {
if (isset($cart[$product->id])) {
$cart[$product->id]['quantity']++;
return $this->setSessionAndReturnResponse($cart);
}
}
return back();
}
public function removeFromCart($id)
{
$cart = session()->get('cart');
if (isset($cart[$id])) {
unset($cart[$id]);
session()->put('cart', $cart);
}
return redirect()->back()->with('success', "Removed from Cart");
}
protected function sessionData(Products $product)
{
return [
'name' => $product->nume,
'quantity' => 1,
'price' => $product->pret,
];
}
protected function setSessionAndReturnResponse($cart)
{
session()->put('cart', $cart);
return redirect()->route('cart')->with('success', "Added to Cart");
}
This is what i have in view file:
<a class="theme_btn add_cart w-100" href="{{route('add.cart', [$produs->id])}}">add to cart
<span class="theme_btn_eff"></span>
</a>
In my loop when i fetch products, on click is redirecting me to 404 page without getting an error, i was trying to get dd($product) into controller but i get again 404.
Change this line
<a class="theme_btn add_cart w-100"
href="{{ route('add.cart', [$produs->id]) }}" >add to cart
<span class="theme_btn_eff"></span>
</a>
To This
<a class="theme_btn add_cart w-100"
href="{{ route('add.cart', ['product' => $produs->id]) }}" >add to cart
<span class="theme_btn_eff"></span>
</a>
In routes file you have passed route parameter naming {product} in url /add-to-cart/{product}, hence you need to mention it in view file as well {{ route('add.cart', ['product' => $produs->id]) }} thats the naming convention laravel follows
Route::get('/add-to-cart/{product}', [CartController::class, 'addToCart'])->name('add.cart');

Creating default object from empty value using laravel 6 and ajax

i have in an annonces table a multiple images, i want to update multiple images, but it gives me error:
Creating default object from empty value knowing that i tried to transform multipleimage to a given json.in the console it gives me the name of the images to select.
AnnoncesController.php
public function filesUpdate(Request $request,$id)
{
$Annonce=Annonce::find($id);
$data = array();
if($request->hasFile('images'))
{
foreach($request->file('images') as $file)
{
$path = $request->images->store('annonces');
$Annonce->images = $path;
array_push($data,$path);
}
}
$Annonce->images = json_encode($data);
$Annonce->save();
return Redirect::to("annonces")
->withSuccess('Great! file has been successfully uploaded.');
}
web.php
Route::post('annonces/filesUpdate','AnnoncesController#filesUpdate');
details.blade.php
<form method="post" action="{{url('annonces/filesUpdate')}}" enctype="multipart/form-data"
class="dropzone" id="dropzone">
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
</form>
<script type="text/javascript">
Dropzone.options.dropzone =
{
maxFilesize: 12,
renameFile: function(file) {
var dt = new Date();
var time = dt.getTime();
var images = time+file.name
console.log(time+file.name);
return images;
},
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
timeout: 50000,
success: function(file, response)
{
console.log(response);
},
error: function(file, response)
{
return false;
}
};
</script>
You are not passing the id as route parameter in the form action so the $id value received in filesUptate method in controller will be null. You have to pass the $Annonce->id as route parameter via form action
//When you send this view as response from edit method you need to pass
//either $Annonce object or at least the $Annonce->id as $AnnonceId to the view
//If you pass the entire $Annonce object then append $Annonce->id as below
//to the form action or replace it with $AnnonceId if you are passing only
//$AnnonceId from the edit method of the controller
<form
method="post"
action="{{url('annonces/filesUpdate/' . $Annonce->id)}}"
enctype="multipart/form-data"
class="dropzone" id="dropzone"
>
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
</form>
The error probably arises as you are trying to call store method on array.
Try the below
public function filesUpdate(Request $request,$id)
{
$Annonce=Annonce::findOrFail($id);
$data = array();
if($request->hasFile('images'))
{
foreach($request->file('images') as $file)
{
//Trying to call store on an array here
//$request->images is not an instance of UploadedFile
//$path = $request->images->store('annonces');
//$file is an instance of UploadedFile
//so you can call store method on it
$data[] = $file->store('annonces');
}
}
$Annonce->images = json_encode($data);
$Annonce->save();
return Redirect::to("annonces")
->withSuccess('Great! file has been successfully uploaded.');
}
You can also use $casts property to let Laravel handle the casting of images attribute automatically
class Annonce extends Model
{
protected $casts = [ 'images' => 'array'];
}

Error in Custom Blade Directives with array as parameter

In my Laravel 5.7 app I want to use Custom Blade Directives and to pass an array in this directive
as there could be different access, like :
#loggedUserHasAccess([USER_ACCESS_ADMIN])
<div class="col">
<a class="social-inner" href="{{ route('admin.dashboard') }}" >
<span class="icon"></span><span>Backend</span>
</a>
</div>
#endLoggedUserHasAccess
And in app/Providers/AppServiceProvider.php :
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
...
\Blade::directive('loggedUserHasAccess', function (array $accessArray) {
$condition = false;
if (Auth::check()) {
$loggedUser = Auth::user();
$usersGroups = User::getUsersGroupsByUserId($loggedUser->id, false);
foreach ($usersGroups as $next_key => $nextUsersGroup) {
if (in_array($nextUsersGroup->group_id, $accessArray)) {
$condition = true;
}
}
}
return "<?php if ($condition) { ?>";
});
Blade::directive('endLoggedUserHasAccess', function () {
return "<?php } ?>";
});
But I got syntax error : https://imgur.com/a/I5s1TmQ
USER_ACCESS_ADMIN is defined in bootstrap/app.php.
looks like my syntax is invalid, but which is valid ?
Thanks!

codeigniter get returned data variable from model in controller and use it in conditional statement

what is wrong with my search implementation, here what i wish to achieve.
view page(form) -> controller(form data variable) -> model(query database and pass to controller) if there's a result return TRUE else return FALSE -> controller(get data from model) if true display data in table else if FALSE display a no results returned message.
here are my pages:
view:
<form action="<?php echo site_url('retrieve')?>" method="post">
<input type="text" name="id">
....
</form>
model:
public function retrieve($id)
{
$search = "SELECT * FROM table";
$result = $this->db->conn_id->prepare($search);
$result->execute();
if($result->rowCount()>0){
return $query_result = $result->fetchAll(PDO::FETCH_ASSOC);
}
}
controller:
public function retrieve_info()
{
$id = $this->input->post('id'),
$this->load->model('search_model');
$this->search_model->retrieve($id);
$data['query_result'] = $this->search_model->retrieve($id);
$this->load->view('display',$data);
}
First the form action is linking to the retrieve function in the controller. However, from your example there is no retrieve function in your controller, only in your model.
view:
<form action="<?php echo site_url('retrieve')?>" method="post">
<input type="text" name="id">
....
</form>
model:
public function retrieve($id)
{
$search = "SELECT * FROM table";
$result = $this->db->conn_id->prepare($search);
$result->execute();
if($result->rowCount()>0){
return $query_result = $result->fetchAll(PDO::FETCH_ASSOC);
}
}
controller:
public function retrieve()
{
if($_POST){
$id = $this->input->post('id'),
$this->load->model('search_model');
$data['query_result'] = $this->search_model->retrieve($id);
$this->load->view('display',$data);
}else {
//form failed to submit via post
}
}

Confirm password field not validating using 'repeated' field using form builder in symfony2 ?

This is how my code snippet looks like.
// --- this is the code in my controller ----
$registrationForm = $this->createFormBuilder()
->add('email')
->add('password', 'repeated', array('type' => 'password', 'invalid_message' => 'Passwords do not match'))
->getForm();
return $this->render('AcmeHelloBundle:Default:index.html.twig', array('form' => $registrationForm->createView()));
// --- This is the twig file code----
<form action="#" method="post" {{ form_enctype(form) }}>
{{ form_errors(form) }}
{{ form_row( form.email, { 'label': 'E-Mail:' } ) }}
{{ form_errors( form.password ) }}
{{ form_row( form.password.first, { 'label': 'Your password:' } ) }}
{{ form_row( form.password.second, { 'label': 'Repeat Password:' } ) }}
{{ form_rest( form ) }}
<input type="submit" value="Register" />
</form>
Can any one suggest why it is not working using form builder?
In Symfony 2, validation is handled by domain object. So you have to pass an Entity (domain object) to your form.
Code in controller :
public function testAction()
{
$registration = new \Acme\DemoBundle\Entity\Registration();
$registrationForm = $this->createFormBuilder($registration)
->add('email')
->add('password', 'repeated', array('type' => 'password', 'invalid_message' => 'Passwords do not match'))
->getForm();
$request = $this->get('request');
if ('POST' == $request->getMethod()) {
$registrationForm->bindRequest($request);
if ($registrationForm->isValid()) {
return new RedirectResponse($this->generateUrl('registration_thanks'));
}
}
return $this->render('AcmeDemoBundle:Demo:test.html.twig', array('form' => $registrationForm->createView()));
}
1) The form builder will map the form fields with the properties of your entity, and hydrate your form field values with your entity property values.
$registrationForm = $this->createFormBuilder($registration)...
2) The bind will hydrate your form fields values with all the data posted
$registrationForm->bindRequest($request);
3 ) To launch validation
$registrationForm->isValid()
4) if the data posted are valid, you have to redirect to an action to inform user that everything is OK, to avoid displaying an alert message from your broswer who ask if your are sure to repost data.
return new RedirectResponse($this->generateUrl('registration_thanks'));
Entity code :
<?php
namespace Acme\DemoBundle\Entity;
class Registration
{
private $email;
private $password;
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
}
public function getPassword()
{
return $this->password;
}
public function setPassword($password)
{
$this->password = $password;
}
}
doc for validation : http://symfony.com/doc/current/book/validation.html
NOTE : there is no need to add some validation on password entity property, the repeatedType done it for you

Resources