Javascript objects keep getting converted to array in laravel backend [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
I started experiencing something strange in my laravel.vuejs application today. When i pass a JS object from vuejs frontend to laravel backend, it gets converted to array. For example, in vuejs
data() {
return {
user: {
name: '',
email: '',
age: ''
},
}
},
methods: {
submit(){
axios.post(this.api + '/test', {
user: this.user
}).then((res) => {
console.log(res.data)
})
}
},
In my laravel controller, print_r($request->user) shows the object as an array.
Array
(
[name] =>
[email] =>
[age] =>
)
How do i fix this? I am using laravel5.8
NB: I noticed this started happening after i ran composer update. Could this be the cause?
NB: After creating the model, I get back a response of array instead of JSON, even after returning the response as JSON. That is the problem.

Object concept doesn't exist in HTTP protocol and you can't send your data with requests as an object. you can get the input as json object and decode it, but that will be a StdClass object. So, you can assign the request array to the user model and use it as an object.
Example:
Suppose you created a User model and you want to assign the array as an attribute.
$user = new User($request->user);
// or
$user = new User();
$user->fill($request->user);
// or
$user = new User();
$user->name = $request->user['name']
$user->age = $request->user['age']
...
Note: It's better to validate the inputs before assign to the user object. you can do it clearly with Form Requests

Related

No Invitations ID [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I have many google classroom invitations and I want to accept all of them through google app script using
Classroom.Invitations.accept("courseId");
but then I get no data back...
so I tried listing all my invitations using
Classroom.Invitations.list({"userId":"my_email"});
and still I get no data back...
I am very sure that my google classroom is full of unaccepted courses
Modification points:
In your script, an error occurs at var teacherEmails=(john.doe#gmail.com,jane.doe#gmail.com);.
I thought that your script might be for a python script. If you want to use this method using Google Apps Script, it is required to modify it.
When these points are reflected in a Google Apps Script, how about the following sample script?
Sample script:
Before you use this script, please enable Classroom API at Advanced Google services.
function myFunction() {
const courseId = "###"; // Please set your course ID.
const teacherEmails = ["john.doe#gmail.com", "jane.doe#gmail.com"]; // Please set email addresses.
teacherEmails.forEach(userId => {
const res = Classroom.Invitations.create({ courseId, userId, role: "TEACHER" });
console.log(res)
});
}
Reference:
Method: invitations.create
Call this method in Google App Script, you will need to use the Classroom.Invitations.create() function in your code and pass the necessary parameters.
function createInvitation() {
var courseId = '1234567890';
var userEmail = 'test#google.com';
var role = 'TEACHER';
var invitation = {
userId: userEmail,
courseId: courseId,
role: role
};
var response = Classroom.Invitations.create(invitation);
Logger.log(response);
}

How to efficiently pull data out of a huge api with multiple pages [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am currently using an API to create a React Redux application. My problem is I am confused about how to efficiently use the data as the API has more than 14470 "pages" to navigate around. My main goal is to display certain items in the API based on key value pair. For example I would say I want to display a category in the API based on a certain key value pair such as "highestRating" and want to map through the API to find out the five items with the highestRating, how would I be able to do this efficiently?
What I have tried so far is looping to get the entire API available to me but then I get stuck with my current task at hand.
export const fetchHighestRating = () => async dispatch => {
let data = [];
let morePagesAvailable = true;
let currentPage = 0;
while (morePagesAvailable) {
currentPage++;
const response = await api.get(
`/api?page%5Blimit%5D=10&page%5Boffset%5D=${currentPage}`
);
data = [...data , response];
morePagesAvailable = currentPage < 17471;
}
dispatch({ type: FETCH_HIGHEST, payload: data });
};
This is not a javascript problem, it is database. You should run query directly in database to test response speed and decide what to do next, including:
Sharding
Indexing
Optimize config of DB
....
Any above required research in type of DB you are using, the current situation of DB so there is no exactly answer now!

How to send an array from an HTML page to Node.js and then store it on a database [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I need help transferring an array made in javascript. I'm confused on how to use node.js and then send it to MySql. Any links to useful videos or an explanation would be appreciated. Thanks
I suggest reading up on this a bit with useful tutorials.
That said, the basic way to do this is to use an NPM package like MYSQL2. You then loop through your array to create an insert statement:
// get the client
const mysql = require('mysql2');
// create the connection to database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test'
});
/*
Assuming your database has a table named `employee` with a two columns: id and name.
Goal: INSERT INTO employee(id,name)
VALUES
(1,"Jerry"),
(2,"Jenny"),
(3,"Jessie"); */
var ary=[{id: 1, name: "Jerry"}, {id: 2, name:"Jenny"}, {id: 3, name: "Jessie"}];
var values = ary.map(a => {
return `(${a.id}, ${a.name})`;
});
// simple query
connection.query(
'INSERT INTO employee(id, name) VALUES ' + values.join(','),
function(err, results, fields) {
console.log(results); // results contains rows returned by server
console.log(fields); // fields contains extra meta data about results, if available
}
);

userId.getUserById is not a function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
When a user click's on a username on the list below, it's meant to open up the add user page with the name's of the user in the fields.
I get this error message:
Here's the code in the manage users page:
componentWillMount: function () {
var userId = this.props.params.id; // from the path /user:id
if (userId) {
this.setState({ user: userId.getUserById(userId) });
}
},
Here's the code in the userApi:
getUserById: function(id) {
var user = _.find(users, {id: id});
return _clone(user);
},
I am new to StackOverflow and programming, so if this post doesn't meet the community's guidelines, please guide me on how to better make use this platform so I can further my learning progression.
Thanks,
Rickie
Using the userId variable you can't call your API. Since getUserById is from your API you must call the method from there.
userApi.getUserById(userId);

What's the best way to check a list of 1 millions codes in Firebase/Cloud function? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am using Firebase with Cloud function to test the good value of a code in a million pre-generated stored in Firebase Realtime Database.
It will be used in a mobile application to verify if a user have buy the bundle in real life.
I found 2 working solutions. In the first, I put the code directly in the name of the property. In the second I put the code in the child property called "key"
In the second case, the key parameter is indexed.
I need a fast (log n complexity) access to get the response.
Do you know if any of my solutions will work for about 1 million entries and 100 calls by second on Firebase.
(I am not familiar with NoSQL.)
In my sample, the codes are "ABCD-0000-000X"
(do not take the property called "user" in consideration)
First Solution : Use the code value as parent
Cloud Function source code
exports.checkKey = functions.https.onRequest((req, res) => {
const code = req.query.code;
return admin.database().ref("Codes/" + code).once("value").then(snapshot => {
if (snapshot.val() === null) {
return res.send("Invalid Code");
}
const nb = snapshot.child("nb");
if (nb.val() > 4) {
return res.send("NO more code");
}
snapshot.ref.update({ "nb": nb.val() + 1 });
return res.send("OK");
});
Second Solution : Use the code in child
exports.getKey = functions.https.onRequest((req, res) => {
const code = req.query.code;
var ref = admin.database().ref("Codes");
ref.orderByChild("key").equalTo(code).on("child_added", function (snapshot) {
const nb = snapshot.child("nb");
if (nb.val() > 4) {
return res.send("NOK");
}
snapshot.child("nb").set(nb.val() + 1);
return res.send("OK");
}
});
Thanks for your help.
There is no way you're going to be able to query a list of one million items. So storing the keys as a property named key is not going to work.
But if you keep the keys as the key of each item, means you can access the item by its path. And that scales really well.
So I'd go with your first approach.
That said: it's hard to recommend anything specific without knowing all use-cases, which nobody (including typically the project creator at an early stage) is likely to know. So I'd also recommend simply learning a bit more about NoSQL data modeling, by reading NoSQL data modeling, watching Firebase for SQL developers, and by experimenting with various approaches before committing to any specific one.

Categories

Resources