How can I update my database properly? I'd like to modify an entry for which I have the id for, but a 'net::ERR_EMPTY_RESPONSE' is returned. Below I have my Controller:
public function update(Request $request, $id)
{
$booking = Booking::query($id);
$booking->start_date = $request->start;
$booking->end_date = $request->end;
$booking->save();
return response()->json($booking);
}
These are all defined in my home blade view:
const eventData = {
id: eventid,
start: arg.event.start.toISOString(),
end: arg.event.end.toISOString(),
};
How do I properly update start_date and end_date in my database?
Additionally, this is my Javascript used to fetch:
const eventid = arg.event.id;
const eventData = {
start: arg.event.start.toISOString(),
end: arg.event.end.toISOString(),
};
const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;
console.log(csrfToken);
fetch(`/api/event/update/${eventid}`, {
method: 'PUT',
headers: {
"X-CSRF-Token": csrfToken
},
body: encodeFormData(eventData),
})
.then(response => console.log(response))
.catch(error => console.log(error));
console.log("Complete");
I'm not sure how you're passing the ID for the booking, but from what I can see on the above, the ID is being passed in the request. Try this:
public function update(Request $request)
{
$booking = Booking::findOrFail($request->id);
$booking->start_date = $request->start;
$booking->end_date = $request->end;
$booking->save();
return response()->json($booking);
}
Updating a record is straight forward all you've got to is
public function update(Request $request)
{
// find the record by it's ID and also update it on the fly if you don't need to process anything else
$updatedData = Booking::findOrFail($request->id)->update(['start_date' => $request->start, 'end_date' => $request->end]);
return response()->json($updatedData);
}
Related
I am doing Paypal integration in Laravel. I have used composer require srmklive/paypal to install the srmklive/paypal package in this project.
When I press the PayPal button, I get this error:
Here is my code:
code from blade file:
paypal.Buttons({
createOrder: function(data, actions) {
return fetch('api/paypal/order/create/', {
method: 'post',
body:JSON.stringify({
"value":100
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},
onApprove: function(data, actions) {
return fetch('/api/paypal/order/capture/', {
method: 'post',
body: JSON.stringify({
orderID: data.orderID
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
var errorDetail = Array.isArray(orderData.details) && orderData.details[0];
if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart();
}
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
return alert(msg); // Show a failure message (try to avoid alerts in production environments)
}
});
}
}).render('#paypal-button-container');
code from paymentController:
class PaymentController extends Controller
{
public function create(Request $request){
$data = json_decode($request->getContent(), true);
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$price = Plan::getSubscriptionPrice($data['value']);
$description = Plan::getSubscriptionDescription($data['value']);
$order = $provider->createOrder([
"intent" => "CAPTURE",
"purchase_units" => [
[
"amount" => [
"currency_code" => "USD",
"value" => $price
],
"description" => $description
]
]
]);
return response()->json($order);
}
public function capture(Request $request) {
$data = json_decode($request->getContent(), true);
$orderId = $data['orderID'];
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$result = $provider->capturePaymentOrder($orderId);
return response()->json($result);
}
}
How can I solve this error?
The route api/paypal/order/create/ is returning/outputting text that is not JSON, such as an HTML error page or something else that begins with an HTML tag.
The route must only output JSON, and must contain a valid id from the PayPal API.
when I try to get data in ajax, the returned object is empty
I send the id of the data I want to get in js :
function selectMessage(id) {
$.ajax({
url: '{{ path('back_translation_update') }}',
method: 'GET',
data: {id: id}
}).done(function (response) {
console.log(response)
})
}
$('.updateMessage').click(function (evt) {
evt.stopPropagation()
selectMessage($(this).data('id'))
})
in the controller I look for the data to return :
/**
* #Route("/update", name="back_translation_update", methods="GET|POST")
*/
public function getById(Request $request): Response
{
if ($request->isXMLHttpRequest()) {
$id = $request->get('id');
// dd($id);
$message = $this->translationService->getTranslationById($id);
// return new JsonResponse(['data' => $message]);
$response = new Response();
$response->setContent(json_encode([
'data' => $message,
]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
I use a service because with the repository I get an error: getById () must be an instance of Symfony\Component\HttpFoundation\Response
with :
$repositoryMessage = $this->em->getRepository(TranslationMessage::class);
$message = $repositoryMessage->findOneBy(['id' => $id]);
so the service will look in the database:
public function getTranslationById($translation_id)
{
$query = $this->em->createQueryBuilder()
->from(TranslationMessage::class,'message')
->select('message')
->where('message.id = ?1')
->setParameter(1, $translation_id);
$message = $query->getQuery()->getResult();
// dd($message);
return $message;
}
all the dd() give the expected values:
into getById(): the id of the row sought
into getTranslationById(): the sought object
but in the XHR, data contains an empty object: uh:
same with a new JsonResponse, commented here
what did I miss? help
Use Aurowire to get messageRepository object and use $this->json() to return JsonResponse
/**
* #Route("/update", name="back_translation_update", methods="GET|POST")
*/
public function getById(Request $request, TranslationMessageRepository $messageRepository): JsonResponse
{
$id = $request->query->get('id');
$message = $messageRepository->find($id);
if(!$message) { return new NotFoundHttpException(); }
return $this->json([
'success' => true,
'data' => $message
]);
}
Define success function instead of done function
function selectMessage(id) {
$.ajax({
url: "{{ path('back_translation_update') }}",
method: 'GET',
data: { id: id }
success: function(data) {
console.log(data)
}
})
}
I am sending some data to my laravel controller using axios get request but the laravel controller shows request null.
my axios request:
const data = {
machine_id: machine_id,
}
const api = "http://192.168.0.108:8000/api/"
const params = JSON.stringify(data)
const headers = {
"Content-Type": "application/json",
}
axios.get(api, { params: params }, headers).then((response) => {
consoleLog("response", response.data)
})
controller:
public function index(Request $request)
{
dd($request->all()); // shows null
}
If I return the response instead of dd() it shows me something like below image:
public function index(Request $request)
{
return $request->all(); // shows data
}
How can I catch the data in controller??
I had the same problem with you. This is what I've done to resolve my problem
let config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}
let params = new UrlSearchParam();
params.append('var1', 'val1');
params.append('var2', 'val2');
//Finally
axios.post('gotourl', params, config).then( ( response ) => {
console.log(response.data);
});
i have an array values in update form. i need to update specific values when user change in textareas. it looks like this
In my vuejs data objects looks like this.
data() {
return {
jobs: [],
details: {
basic_id: this.$route.params.id,
work: this.jobs
}
};
},
and my update method i wrote like this.
updateDetails() {
this.loading = true;
this.updateWorkedPlaces(this.details)
.then(() => {
console.log("success");
this.loading = false;
})
.catch(() => {
this.loading = false;
});
}
i pass these values it my vuex action methods.
async updateWorkedPlaces({ commit }, payload) {
let job = await Api().put("works/" + payload.basic_id, payload.work);
commit("UPDATE_WORK", job);
},
i pass these values to my laravel backend update function. it looks like this.
public function update(Request $request, $id)
{
$work = $request->work;
$basic = $request->basic_id;
foreach ($request->work as $i => $id) {
$job = Job::findOrFail($basic);
$job->fill(['position' => $id['position'], 'address' => $id['address']])->save();
}
return response()->json(['message' => 'success']);
}
but when i pass these values to this function it shows me this error.
Invalid argument supplied for foreach()
how can i fix this error. anyone can help me?
i figure out my problem with this function
public function update(Request $request, $id)
{
$collection = $request->all();
for ($i = 0; $i < count($collection); $i++) {
Job::where('id', $collection[$i]['id'])
->update([
'position' => $collection[$i]['position'],
'address' => $collection[$i]['address']
]);
}
return response()->json(['collection' => $collection]);
}
I have a controller called CartController.php
In this controller I have two methods:
public function store(Request $request)
{
// we'll check to see if the order is already in db
$productOrderDetails = new \App\Cart;
$productOrderDetails->session_id = session()->getId();
$productOrderDetails->job_name = $request->jobName;
$productOrderDetails->pro_name = $request->productName;
$productOrderDetails->save();
return response()->json($request);
}
public function displayCart()
{
//dd($upsCost);
$currentSessionID = session()->getId();
$displayCart = Cart::where('session_id', $currentSessionID)->get();
dd($currentSessionID);
session(['inCartDetails' => $displayCart]);
return view('layouts.cart')->with('cartDetails', $displayCart);
}
The store method is hit by a fetch api post.
export async function postProductDetails(details) {
const url = 'http://127.0.0.1:8000/api/cartDetails';
let response = await fetch(url, {
method: 'POST',
mode: 'cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(details)
})
if(response.ok) {
window.location.href = "/cart";
} else {
alert("HTTP-Error: " + response.status);
}
// return response.json();
}
My problem is that I'm getting two different session ids.
When the method store is hit via the fetch post I get the session id:
HnSxCjSXflzyt4Uks3SGsEZcJEHleSR97N1RNA5l
Then when I run the method displayCart it gives me a different session id:
su8A6E3umTW1XmXf5Yhk3SHU5WUGCEpcJWXlnVIP
It's being accessed from same browser, with in a couple of minutes. Any idea why this is happening?
I would not rely on the session ID for your logic, You could however create a Cart and save the Cart ID to the session and then retrieve it:
public function store(Request $request)
{
$productOrderDetails = new \App\Cart;
$productOrderDetails->job_name = $request->jobName;
$productOrderDetails->pro_name = $request->productName;
$productOrderDetails->save();
session(['cart_id' => $productOrderDetails->id]);
return response()->json($request);
}
public function displayCart()
{
$displayCart = session('cart_id') ? Cart::find(session('cart_id')) : null;
return view('layouts.cart')->with('cartDetails', $displayCart);
}