I have a Vue.js form and I submit the form using Axios. I'm able to save the data to my database. However, when I want to save my dynamically added input fields I get this error message...
Invalid argument supplied for foreach
The problem is that it's not an array but it should be. As you can see, I would like to send the teams[] array from the Vue component to the Laravel backend with Axios. When i console.log() teams [object object], [object object].
app.js
new Vue({
el: '#regapp',
data: {
username: '',
email: '',
password: '',
password_confirmation: '',
teams: [
{
name: '',
role: '',
linkedin: '',
profileimg: ''
}
],
methods: {
onSubmit() {
axios.defaults.headers.common["X-CSRF-TOKEN"] = document
.querySelector('meta[name="csrf-token"]')
.getAttribute("content");
let formData = new FormData();
formData.append('username', this.username);
formData.append('email', this.email);
formData.append('password', this.password);
formData.append('password_confirmation', this.password_confirmation);
formData.append('teams', this.teams);
axios.post('register', formData)
.then(response => alert('Success'))
.catch(error => this.errors.record(error.response.data.errors));
}
}
}
});
Controller.php
protected function create(array $data)
{
$user = new User();
$user->name = $data['username'];
$user->email = $data['email'];
$user->password = Hash::make($data['password']);
$user->save();
// Here I try to loop trough teams and save each of them names into db.
if ($data['teams'][0] != NULL) {
$format = (array)$data;
foreach ($format['teams'] as $teams) { // The error is here
$team = new Team();
$team->user_id = $user->id;
$team->tmembername = $teams->name;
$team->save();
}
}
return $user;
}
Thanks Hassan for the help.
The problem was that this.teams is an array of objects - it just tries to convert the Object to a String, hence getting [object Object].
So i can't do this:
formData.append('teams', this.teams);
I had to:
var teammemb = JSON.stringify(this.teams);
Then:
formData.append('teams', teammemb);
On my RegisterController.php
$csapat = (json_decode($data['teams']));
if (is_array($csapat) || is_object($csapat)) {
// in this contition, foreach gonna work only array or object exist
foreach ($csapat as $teams) {
$team = new Team();
$team->ico_id = $ico->id;
$team->tmembername = $teams->name;
$team->save();
}
}
It works now.
Related
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);
}
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.
The built in behavior for flashing back validation errors in Laravel does not seem to be working for my use case.
I have a (React) form that posts it's data via fetch API using this method, which reloads or redirects the page with (hopefully) any session data after the response is returned:
fetch(props.register_route, {
method: 'POST',
headers: {
'X-CSRF-Token': props.csrf,
},
body: data,
})
.then((result) => {
return result.json();
})
.then((result) => {
console.log(result);
window.location.href = result.url;
},
(error) => {
console.log(error);
});
In my controller, I validate this data but if I structure it as follows, the errors are not available as $errors in the resulting page
if ($validator->fails()) {
return redirect()->back()->withErrors($validator);
}
However if I manually flash the errors to the session and return a url instead of a redirect, suddenly the behavior works.
if ($validator->fails()) {
Session::flash('errors', $validator->errors());
return response->json([
'url' => route('register'),
], Response::HTTP_NOT_ACCEPTABLE);
}
I feel as if I must be doing something incorrectly here to have to use this workaround. I could also manually send the errors back in the response, which may be the right way to structure things in the long run.
when you are calling api from javascript or front end applications like Reactjs,Angular,android etc.. .So it expect return result should be in json format so it should be like
if ($validator->fails()) {
return response()->json( $validator->errors(),422);
}
if you not calling Method from direct laravel blade then pass response in JOSN Format.
like
https://laravel.com/docs/8.x/responses#json-responses
Or
make one ResponseManager File
<?PHP
namespace App\Libraries\utils;
class ResponseManager {
public static $response = array('flag' => true, 'data' => '', 'message' => '', 'code' => 01,);
public static function getError($data = '', $code = 10, $message = '', $flag = false) {
self::$response['flag'] = $flag;
self::$response['code'] = $code;
self::$response['data'] = $data;
self::$response['message'] = $message;
return self::$response;
}
public static function getResult($data = '', $code = 10, $message = '', $flag = true) {
self::$response['flag'] = $flag;
self::$response['code'] = $code;
self::$response['data'] = $data;
self::$response['message'] = $message;
return self::$response;
}}
Define in config/app.php
//custom class
'ResponseManager' => App\Libraries\utils\ResponseManager::class,
and then use in whole project
Error Message Like
if ($validation->fails()) {
$message = $validation->messages()->first();
return Response()->json(ResponseManager::getError('', 1, $message));
}
Success Message Like
return Response()->json(ResponseManager::getResult(null, 10, "Success"));
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 am developping an application and I got a problem in my front-end part. It's related to Symfony and Ajax. So I am using a session variable in order to add a student to a school before sending the form of school to the server (back-end). I am using then some Ajax. I do not how to debug it. I tried what it is posted in the net but it does not work. I was able to add a student to a school but I was not able to update the student information. That's seem easy but it's not as I thought. Here is an ajax call that I am using in my SchoolCreate.html.twig:
function ajax () {
$.ajax({
type: 'POST',
url: "{{ path('student_add') }}",
data: $('#addStudent').serialize(),
success: function (response) {
var htmlToDisplay = response.trim();
$('#students').html(htmlToDisplay);
}
});
}
My modal used to create school:
<div class="modal-body">
{{ render(controller('AppBundle:School:addStudent')) }}
</div>
addStudent:
public function addStudentAction(Request $request) {
$student = new Student();
$form = $this->createForm(StudentType::class, $student);
$form->handleRequest($request);
$headers = array('Accept' => 'application/json');
$encoders = array(new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
if ($request->isXmlHttpRequest())
{
$session = $request->getSession();
$student = $form->getData();
if ($session->has('students'))
$students = $session->get('students');
$students[] = $student;
$session->set('$students', $students);
$template = $this->renderView('AppBundle:School:StudentList.html.twig', array(
'students' => $students
));
return new Response($template);
}
return $this->render('AppBundle:Student:StudentAdd.html.twig', array(
'form' => $form->createView()
));
}
I try to do the same in updateStudent function but I got a problem related to 30 second exceeded and I do not know how to debug in Ajax. I define my bottom of update inside StudentList.html.twig
Thanks,