Parse Javascript - Relation is not a function - parse-platform

I'm trying to understand how relation works and i did wrote this simple script:
var Parse = require('parse/node');
Parse.initialize('myAppId');
Parse.serverURL = 'http://localhost:1337/parse';
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo('username', 'the_username');
userQuery.find()
.then(user => {
return user;
})
.then(user => {
var Systems = Parse.Object.extend("systems");
var systemQuery = new Parse.Query(Systems);
systemQuery.equalTo('customer', 'myCustomer');
systemQuery.find()
.then(system => {
var relation = user.relation('systems_ref'); // HERE I GET RELATION IS NOT A FUNC
relation.add(system);
console.log('Adding relation');
user.save()
.then(response => console.log('user saved'))
.catch(error => console.log('Error saving', error));
}).catch(error => console.log('Error find system', error));
});
But in the line where i try to get user.relation i have the error "Relation is not a function".
I have look others example on how to create a relation, but i dont see difference in my code...
I have the user (that is a sublcass of ParseObject), and on it i'm trying to access relation method...

You may use it as follows:
To add the Post to User with the JavaScript SDK:
var user = Parse.User.current();
var relation = user.relation("posts");
relation.add(post);
user.save();

Related

how to set and get session with koajs and koa-session?

im already read from the documentation and also find some tutorial like tutorialspoint. But, so far i dont know how to create and use session with koa. Here's my code:
router.post('/login', async ctx => {
const user = ctx.request.body
const name = user.name
const email = user.email
const password = user.password
const users = require('./client').db('mydatabase').collection('users')
const userExist = await users.findOne({"name": name})
const emailExist = await users.findOne({"email": email})
if(userExist || emailExist) {
this.session.email = email
ctx.body = this.session.email
}
})
above code give error below:
TypeError: Cannot set properties of undefined (setting 'email')
Previously i've learn a lot from laravel, Here's how we create and use the session with laravel:
//creating session
...
session([
'email' => $request->input('email')
])
...
//use session
$email = session('email')
...
can you tell me? or do you have better example? Thanks

On get request why do I get back the blade view, when I should get data from the database instead?

I a have the following get request, which is executed on mounted().
In some weird mysterious ways, I get back my main view app.blade as a response when I am clearly requesting some data from the database.
Can someone spot what I messed up?
My get request on the front-end:
mounted() {
this.getProjectRequests();
},
methods: {
getProjectRequests: function() {
var self = this;
let clientId = this.$route.path.substring(
this.$route.path.lastIndexOf("/") + 1
);
axios({
method: "get",
url: "/get-project-requests/" + clientId
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
// TODO error handling
});
}
}
My route:
Route::get('/get-project-requests/{client_id}',
'SinglePageController#getProjectRequests');
And my controller method:
public function getProjectRequests($clientId) {
try {
$projectRequests = ProjectRequest::where('client_id',
$clientId)->value('name');
return response()->json( [
'success'=> true,
'projectRequests' => $projectRequests
]);
} catch(\Exception $e){
return ['success' => false, 'message' => 'getting
project requests failed'];
}
}
I think this ProjectRequest::where('client_id', $clientId)->value('name'); giving exception.
Either you check your laravel.log inside storage/logs folder or change that method into
// Not working on eloquent model
$valueOject = ProjectRequest::where('client_id',$clientId)->value('name');
// DB facade its working. Change to this method
$valueOject = DB::table('{your_table}')->where('client_id', $clientId)->value('name');
dd($valueOject);

How to have multiple passport for different user types in MEAN stack

In my project, I am using the passport feature in MEAN stack for user authentication. I have logins for 4 different user types(patient , doctor , and so on.) Can I have multiple passports for all different user types??
Below mentioned is the code for User(patient) Passport. I tried creating different passports, but I don't know how to link them to the project.
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
var User = mongoose.model('User');
passport.use(
new localStrategy({ usernameField: 'email' },
(username, password, done) => {
User.findOne({ email: username },
(err, user) => {
if (err)
return done(err);
// unknown user
else if (!user)
return done(null, false, { message: 'Email is not registered' });
// wrong password
else if (!user.verifyPassword(password))
return done(null, false, { message: 'Wrong password.' });
// authentication succeeded
else
return done(null, user);
});
})
);

Sending FormData() with axios in VueJS returns empty array in Laravel

I am trying to post my data using FormData() with axios. Laravel is my Backend.
When I try to dd (die and dump) my $request->all() in my Controller I get an empty array [].
Here's my code which handles the post:
data() {
let formData = new FormData();
formData.append('first_name', 'Max');
formData.append('first_name', 'Sample');
return formData;
}
submit(requestType, url) {
console.log(this.data().get('first_name')); // Output is correctly 'Max'
return new Promise((resolve, reject) => {
axios[requestType](url, this.data())
.then(response => {
this.onSuccess(response.data);
resolve(response.data);
})
.catch(error => {
this.onFail(error.response.data)
reject(error.response.data);
});
});
}
sendData() {
const id = 123;
this.submit(patch, '/persons/' + id);
}
However if I format my data like this:
data() {
let data = {
'first_name': 'Max',
'last_name': 'Sample'
};
return data;
}
I have the right output with dd($request->all() in my Controller.
EDIT
I found the reason for my problem. It is related to the HTTP method patch. If I use post instead the data is send successfully. It must be related to the headers being send but I could not find a solution yet.

Invalid argument Supplied for foreach() Axios Laravel

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.

Resources