MethodNotAllowedHttpException When i'm using Post Method [gloudemans-package] - php

recently I'm trying to create a shopping cart for my assignment project. I'm quite new to this framework, sorry if I asked something stupid :( It's a pleasure for me if you guys can check it for me. Tks
I'm also trying to switch to GET method but still didn't work
The error were:
MethodNotAllowedHttpException
This is my controller
public function cart() {
if (Request::isMethod('post')) {
$product_id = Request::get('product_id');
$product = Product::find($product_id);
Cart::add(array('id' => $product_id, 'name' => $product->name, 'qty' => 1, 'price' => $product->price));
}
if (Request::get('product_id') && (Request::get('increment')) == 1) {
$rowId = Cart::search(array('id' => Request::get('product_id')));
$item = Cart::get($rowId[0]);
Cart::update($rowId[0], $item->qty + 1);
}
if (Request::get('product_id') && (Request::get('decrease')) == 1) {
$rowId = Cart::search(array('id' => Request::get('product_id')));
$item = Cart::get($rowId[0]);
Cart::update($rowId[0], $item->qty - 1);
}
$cart = Cart::content();
return view('cart', array('cart' => $cart, 'title' => 'Welcome', 'description' => '', 'page' => 'home'));}
This is my Route
Route::post('cart', 'HomepageController#cart')->name('cart');
This is my view
#extends('layout')
#section('cart')
<section id="cart_items">
<div class="container">
<div class="breadcrumbs">
<ol class="breadcrumb">
<li>Home</li>
<li class="active">Shopping Cart</li>
</ol>
</div>
<div class="table-responsive cart_info">
#if(count($cart))
<table class="table table-condensed">
<thead>
<tr class="cart_menu">
<td class="image">Item</td>
<td class="description"></td>
<td class="price">Price</td>
<td class="quantity">Quantity</td>
<td class="total">Total</td>
<td></td>
</tr>
</thead>
<tbody>
#foreach($cart as $item)
<tr>
<td class="cart_product">
<img src="images/cart/one.png" alt="">
</td>
<td class="cart_description">
<h4>{{$item->name}}</h4>
<p>Web ID: {{$item->id}}</p>
</td>
<td class="cart_price">
<p>${{$item->price}}</p>
</td>
<td class="cart_quantity">
<div class="cart_quantity_button">
<a class="cart_quantity_up" href=""> + </a>
<input class="cart_quantity_input" type="text" name="quantity" value="{{$item->qty}}" autocomplete="off" size="2">
<a class="cart_quantity_up" href='{{url("cart?product_id=$item->id&increment=1")}}'> + </a>
<a class="cart_quantity_down" href='{{url("cart?product_id=$item->id&decrease=1")}}'> - </a>
</div>
</td>
<td class="cart_total">
<p class="cart_total_price">${{$item->subtotal}}</p>
</td>
<td class="cart_delete">
<a class="cart_quantity_delete" href=""><i class="fa fa-times"></i></a>
</td>
</tr>
#endforeach
#else
<p>You have no items in the shopping cart</p>
#endif
</tbody>
</table>
</div>
</div>
</section> <!--/#cart_items-->
#endsection

You are using a tags, this won't do a POST request, instead, the browser is gonna follow the link to make a GET request. That's why you are getting MethodNotAllowedHttpException since it's only expecting a POST request at that endpoint. The same issue will happen with the delete button you have.
This will be complicated to give you a complete solution in an answer. For what you are trying to do, there are several paths you can take to make this work.
you can have a form(s) in your HTML to make a POST request and probably use buttons to post the increment and decrement the quantity, and/or delete, then reload the page with updated quantity.
you can handle the increment/decrement/delete on the frontend using JS and updating the quantity field and finally submit the form with another button (e.g. Checkout Button).
You can also, make this simpler using a framework like Vue/React to
easily handle the cart behavior/function with reactivity.
Notes:
you should not need to check Request::isMethod('post') if you only mapped it to POST in your routes. You should have 1 method per endpoint anyways.
consider using FormValidation instead of explicitly checking if a value was sent or not https://laravel.com/docs/8.x/validation
You might want to redirect to a show method after updating instead of returning a view.
Example:
<td class="cart_quantity">
<div class="cart_quantity_button">
<form action="{{ url('cart') }}" method="post">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="product_id" value="{{ $item->id }}">
<button type="submit" class="cart_quantity_up" name="increment"> + </button>
<input class="cart_quantity_input" type="text" name="quantity" value="{{$item->qty}}" autocomplete="off" size="2" readonly>
<button type="submit" class="cart_quantity_down" href='{{url("cart?product_id=$item->id&=1")}}' name="decrease"> - </button>
</form>
</div>
</td>

Related

Laravel Function called by Route returning '500' error. DB data

public function saveUserToGroup(Request $request, $username){
if (!$this->secure($username)) return redirect('/404');
$member = new UserHobby();
$person = $request->input('person');
$group = $this->group;
$member->user_id = $person->id;
$member->hobby_id = $group->id;
if ($member->save()) {
$request->session()->flash('alert-success', 'Your friend has been added to the group!');
}else{
$request->session()->flash('alert-danger', 'Something went wrong!');
}
return Redirect::back()->withErrors(['msg', 'Success']);
}
<form action="/social/{username}/save/group" method="POST">
#csrf
<table id="modal-table">
#foreach($user_list->get() as $f)
<tr>
<td>
<div class="image">
#if($f->follower->avatar_location)
<img src="{{asset('storage/'.$f->follower->avatar_location)}}" class="img-circle" style="max-height:50px;" />
#else
<img src="{{url('/')}}/assets/media/icons/socialbuttons/user.png" class="img-circle" style="max-height:50px;"/>
#endif
</div>
<div class="detail">
#if($f->follower->verified == 1)
{{ $f->follower->name }}<img id="verified_img_sm_mess_list" src="{{url('/')}}/assets/media/icons/socialbuttons/octagonal_star.png" alt="Recensioni">
#else
<h3>{{ $f->follower->name }}</h3>
#endif
<small id="mess_list_uname">{{ '#'.$f->follower->username }}</small>
</div>
<button type="submit" name="person" value="person" class="btn-link">Go</button>
</td>
</tr>
#endforeach
</table>
</form>
Route::post('/social/{username}/save/group', [GroupController::class, 'saveUserToGroup'])->name('socialprofile.save.user.group');
Hey guys, I'm new to all this, and not sure if I'm calling the route incorrectly or wrong application of my controller function. Obviously I'm trying to add a user from a list into a group. Please Help! I've been a little lost with this and looking for some help to understand where my errors are. Many thanks!
EDIT**
now log reading..
"'hobby_id' cannot be null"..
I have tried to change the variable to take the group id. and that reads error "trying to get id of non-object"
but am I not assigning hobby_id as the group_id?
The problem is that I want to add into 'hobby_id' the 'id' of the current group which this function is being called.

is there any solution to face the Error: Call to a member function myfunction() on array in?

I am facing some errors with my code, actually I've read another same problem, but I cannot catch the point to solve this error, I'm using controller to fetch almost all table called including ppdb, <-- this table show errors Fatal Error Call to a member function getPdb() on array in line 64
this my code
<tbody>
<?php
$no = 1;
if(is_array($data->getPdb()) || is_object($data->getPdb())){ //This line 64
foreach($data->getPdb() as $data){?>
<tr>
<td><?=$no++?></td>
<td><?=$data['gelombang']?></td>
<td><?=$data['tanggalbuka']?></td>
<td><?=$data['tanggaltutup']?></td>
<td><?=$data['tahunajaran']?></td>
<td><?php if($data['status']==1){echo 'Aktif';}else{echo 'Tidak Aktif';}?></td>
<td>
<i class="fa fa-<?php echo (($data['status']==2)?'check':'check');?>"></I>&nbsp<?php echo (($data['status'] == 2)?'AKtifkan':'Non Aktifkan');?>
</td>
</tr>
<?php } } ?>
</tbody>
in my controller the code written like this:
$getta = $this->pdo->prepare("SELECT * FROM ppdb");
$getta->execute();
$c = $getta->rowcount();
if($c > 0){
foreach($getta as $data){
$hasil[] = $data;
}
return $hasil;
}
}
And the error shown like this
Fatal error: Uncaught Error: Call to a member function getPdb() on array in D:\xampp\htdocs\nh\inc\view\admin\inc\ppdb.php:64 Stack trace: #0 D:\xampp\htdocs\nh\inc\view\admin\index.php(31): include() #1 {main} thrown in D:\xampp\htdocs\nh\inc\view\admin\inc\ppdb.php on line 64
Above this table I use another function to save the form and fetch the option:
<form class="form animated bounceIn" method="POST">
<div class="form-group">
<?php
$data->createPpdb();
?>
</div>
<div class="card">
<div class="card-header bg-dark">
Setting Gelombang PPPDB
</div>
<div class="card-body">
<div class="form-group">
<input type="text" name="gelombang" title="Nama Gelombang" class="form-control" placeholder="contoh: Gelombang I">
</div>
<div class="form-group">
<input type="text" name="tanggalbuka" title="Tanggal Buka PPDB" class="form-control" placeholder="Pilih Tanggal" id="tbuka">
</div>
<div class="form-group">
<input type="text" name="tanggaltutup" title="Tanggal Tutup PPDB" class="form-control" placeholder="Pilih Tanggal" id='ttutup'>
</div>
<div class="form-group">
<select class="form-control" name="ta">
<option value="" disbaled>-Pilih Tahun Ajaran-</option>
<?php
if(is_array($data->getTa()) || is_object($data->getTa())){
foreach($data->getTa() as $data){?>
<option value="<?=$data['tahunajaran']?>"><?=$data['tahunajaran']?></option>
<?php
}
}
?>
</select>
</div>
</div>
<div class="card-footer">
<div class="form-group">
<input type="submit" name="simpanppdb" class="btn btn-sm btn-success" value="Simpan">
</div>
</div>
</div>
</form>
I'd read with similar problem from stacoverflow.com but I cannot get the point.
Thank you for someone who save my day.
The problem is that you're reusing the variable $data in the line:
foreach($data->getPdb() as $data){
So $data starts out being an object, but after the loop it contains the last row of the results, which is an array. The next time you try to call $data->getPdb() you'll get an error.
Use different variables, like this:
foreach ($data->getPdb() as $item) {
Also, you shouldn't call $data->getPdb() repeatedly. Each time you do is_array($data->getPdb()) and is_object($data->getPdb()) it performs the full query and collects all the results. Do it once and save the result in a variable.
$pdb = $data->getPdb();
if (is_array($pdb) || is_object($pdb)) {
foreach ($pdb as $item) {
...
}
}
Thank you for your answer all, I've solved this with my own way and it took from Mr. #Braham comment, I try to combine the variable and re-initiate the class.
this the solving problem
<table class="table table-hover" id="ppdb">
<thead>
<tr>
<th>No</th>
<th>Gelombang</th>
<th>Tanggal Buka</th>
<th>Tanggal Tutup</th>
<th>Tahun Ajaran</th>
<th>Status</th>
<th>Opsi</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$item = new NurulHuda(); // This re-initiate Class
if(is_array($item->getPpdb()) || is_object($item->getPpdb())){
foreach($item->getPpdb() as $val){?>
<tr>
<td><?=$no++?></td>
<td><?=$val['gelombang']?></td>
<td><?=$val['tanggalbuka']?></td>
<td><?=$val['tanggaltutup']?></td>
<td><?=$val['tahunajaran']?></td>
<td><?php if($val['status']==1){echo 'Aktif';}else{echo 'Tidak Aktif';}?></td>
<td>
<i class="fa fa-<?php echo (($val['status']==2)?'check':'check');?>"></I>&nbsp<?php echo (($val['status'] == 2)?'AKtifkan':'Non Aktifkan');?>
</td>
</tr>
<?php } } ?>
</tbody>
</table>
Thank you Mr. #Braham for lighting me...

Can't delete from SQLite table in Laravel

I'm Doing a "take home assignment" for job interview. While I have some experience in web development, its not my forte. I am trying to delete a row in a SQLite table using a HTML DELETE button. I am using Laravel-php framework.
I've tried different solutions on google and stack Overflow, but none seem to solve the problem. I modeled my approach after this Laracasts video
Link to my code
The blade seems to be passing the correct info ($id from $contact->id) & the controller seems to be receiving. But the given contact associated with the id isn't being deleted.
FROM BLADE:
<div class="col-md-6">
<table class="table table-striped table-hover">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
</tr>
#foreach($contacts as $contact)
<tr>
<td> {{$contact->f_name}} </td>
<td> {{$contact->l_name}} </td>
<td> {{$contact->address}} </td>
<td>
<form method="POST" action="/delete/{{ $contact->id }}">
#method('DELETE')
#csrf
<div class="field">
<div class="control">
<button type="submit" class="button">Delete Contact</button>
</div>
</div>
</form>
</td>
</tr>
#endforeach
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
FROM CONTROLLER:
public function delete($id) {
Contact::find($id)->delete();
return view('index');
}
FROM ROUTE:
Route::delete('/delete', [
'uses'=>'ContactController#delete',
'as'=>'contacts.delete'
]);
you're not getting the id on your delete method, you need to include it on the url like
Route::delete('/delete/{id}', [
'uses'=>'ContactController#delete',
'as'=>'contacts.delete'
]);
in this case, you don't need to change the delete method.
you can also retrieve the id from the request object without changing the delete route, int this case you need to include the id as a hidden input on your view and your delete method will look like this
public function delete(Request $request) {
Contact::find($request->id)->delete();
return view('index');
}

Laravel "No query results for model [App\Schedule]" error when not calling model

I have a perplexing issue that I cannot seem to figure out. I am trying to load a webpage from a button, but it keeps poping up the error No query results for model [App\Schedule]. I have no idea why it's doing that, as there is nowhere I am trying to access that model when trying to load the webpage. Below is what I have so far (it's a work in progress)
Here is the link:
<a class="btn btn-primary" role="button" href="/schedule/availability">Set Availability</a>
Here is the Route:
Route::get('/schedule/availability', 'ScheduleController#getAvailabilityCalendar');
Here is the method inside of the ScheduleController:
public function getAvailabilityCalendar(){
$dt = Carbon::now('America/Los_Angeles');
$return['DayOfWeek'] = $dt->dayOfWeek;
$return['DisplayDays'] = (($dt->daysInMonth + $return['DayOfWeek'] + 1) <= 35) ? 34:41;
return view('contractors.availability', compact('return'));
}
And here is the view that is returned:
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Sunday </th>
<th>Monday </th>
<th>Tuesday </th>
<th>Wednesday </th>
<th>Thursday </th>
<th>Friday </th>
<th>Saturday </th>
</tr>
</thead>
<tbody>
<tr>
#for ($i = 0, $j=-$return['DayOfWeek']; $i <= $return['DisplayDays']; $i++, $j++)
#if($i < $return['DayOfWeek'])
<td></td>
#else
#if($i %7 == 0)
</tr><tr>
#endif
#if($j < 30)
<td>{{\Carbon\Carbon::now('America/Los_Angeles')->addDays($i-$return['DayOfWeek']+1)->format('F jS')}}
<hr>
<div class="form-group">
<label data-toggle="popover" data-trigger="hover" data-content="Add Times available in the following format: 10:00am-4:00pm. You may also add multiple blocks of time separated by comma. Example: 10:00am-12:00pm, 2:00pm-4:00pm">Available Time</label>
<input type="text" class="form-control availability" />
</div>
<div class="checkbox">
<label>
<input type="checkbox" class="all-day-check" />All Day</label>
</div>
</td>
#else
<td></td>
#endif
#endif
#endfor
</tr>
</tbody>
</table>
</div>
<script>
$(document).on('change', '.all-day-check', function(){
if (this.checked) {
$(this).closest("input.availability").prop("disabled", true);
}else{
$(this).closest("input.availability").prop("disabled", false);
}
});
</script>
I can't find anywhere that would need a reference to the App\Schedule model, which is a model in my project. I am at a total loss as to what it could be or why it's trying to run something I never asked it to run.
Edit: There is also no other instance of /schedule/availability in the routes file as well, I triple checked.
Update: Here is the Constructor for ScheduleController:
public function __construct()
{
$this->middleware('auth'); //Check is user is logged in
}
Here is the stacktrace I received (For some reason, it didn't show up in my error log so I only have the screenshot)
As it turns out in the discussion in comments above. The culprit is narrowed down to a conflicting route.
Route:something('/schedule', ...)
was found before
Route::get('/schedule/availability', 'ScheduleController#getAvailabilityCalendar');
and the Route:something fires before the desired route. It should be noted that route defined first will be the first one to serve. This is the reason why Route:resource should be put after your custom Route:get or another routes to avoid confusion.
Next item in the list when changing routes but it does not updated, alwasy fire a php artisan route:clear. It will clear the route caches - can check in the docs.

passing session variable in laravel 5.2

I have the modal where I am processing the data in the modal and then I need to store 1 value and pass it to the next page but then for some reason it is not working.
My modal code :- I have the variable $doctorName already set
session(['doctorName' => $doctorName]);
My view file
<div class="col-sm-12 row2">
<table width="100%">
<tr>
<td>
<p>Second Opinion from
<br /><span id="dr_Name"></span></p>
</td>
{{ session('doctorName') }}
<td align="right">
<p>INR 3000/-</p>
</td>
</tr>
</table>
</div>
Try {!! session('doctorName') !!} instead of {{ session('doctorName') }}
Do you open new view after modal? Maybe you need:
return view('someview')->with('doctorName');

Categories