Recover item id in v-for loop - laravel

I am trying to build response to comment. Here is what I am trying to do:
I take the comment ID from the v-for loop and put it in a span that is invisible. Then I want to recover the value of id in 'pm' variable In function call have(), then send it to my controller to insert data in DB. But nothing happens and it shows an error that he can recover the id.
this my vue ProjectDeatil.vue:
<div class="form-group" style="display: inline;" >
<form #submit.prevent="ajouterCommentaire()">
<label>Votre Commentaire:</label>
<div class="input-group input-group-sm mb-0">
<input class="form-control form-control-sm" v-model="form.body" type="text" name="body"
:class="{ 'is-invalid': form.errors.has('body') }" placeholder="commenter.." style="width:450px;">
<has-error :form="form" field="body"></has-error>
<div class="input-group-append">
<button type="submit" class="btn btn-success " >Commenter</button>
</div>
</div>
</form>
</div>
<div v-for="comment in comments" :key="comment.id" class=" align-items mt-3">
<span id="pm" :value="comment.id" style="">{{ comment.id }}</span>
<hr>
<span class="badge badge-primary"> {{ comment.comment_user_name }}</span > {{ comment.body }}
<b> <small class="badge badge-success" style="float:right; color:#2d132c " >Posté le {{ comment.created_at || date }} </small></b>
<br>
<button #click="showbtn(comment.id)" class="btn btn-default" >Répondre</button>
<form #submit.prevent="ajouterCommentaireReponse()" v-bind:id="comment.id " class="d-none">
<div class="input-group input-group-sm mb-0">
<input class="form-control form-control-sm " type="text" name="body"
placeholder="commenter.." style="width:450px;">
<div class="input-group-append">
<button type="submit" class="btn btn-success " >Commenter</button>
</div>
</div>
</form>
<hr>
</div>
</div>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
</div>
</div>
<!-- /.row -->
<!-- /.row -->
</div>
<!-- /.card-body -->
</div>
</div>
</template>
<script>
export default {
data(){
return{
key: this.$route.params.id,
projets:[],
projet:{
id:'',
name:'',
durre:'',
description:'',
budget:'',
owner:'',
},
membres:[], membre:{
id :'',
membre:'',
projet_id:'',
},
form : new Form({
id:'',
body:'',
user:'',
}),
comments:[],
comment:{
id:'',
body:'',
created_at:''
}
}
},
methods:{
afficherProjets(){
axios.get('/api/getProjects')
.then(({data}) => {this.projets=data.data});
},
afficherMembre(){
axios.get('/api/membreid').then(({data})=> {this.membres =data.data});
},
ajouterCommentaire(){
this.form.post('/api/comments/'+this.key).then(()=>{
this.form.reset()})
},
ajouterCommentaireReponse(){
axios.post('/api/commentsreponse/'+ this.have()).then(()=>{
})
},
afficherComments(){
axios.get('/api/comments').then(({data})=> {this.comments =data.data});
},
showbtn(id){
let element= document.getElementById(id);
element.classList.toggle('d-none');
},
have(){
var key = document.getElementById('pm').value;
return key;
}
},
mounted() {
console.log('Component mounted.')
this.afficherProjets();
this.afficherMembre();
this.afficherComments();
}
}
</script>
this is my function controller:
public function storereply($key){
//$data =$request->all();
$commentaire=Commentaire::find($key);
$commentairereply =new Commentaire;
$commentairereply->user_id= auth()->user()->id;
$commentairereply->body= request('body');
$commentairereply->comment_user_name=$commentaire->user->name;
$commentaire->comments()->save($commentairereply);
}
and this is my route:
Route::post('/commentsreponse/{key}', 'API\CommentController#storereply');

You need to make sure comment.id can actually reach the have function. Simply pass it as an argument to ajouterCommentaireReponse:
<form #submit.prevent="ajouterCommentaireReponse(comment.id)" v-bind:id="comment.id " class="d-none">
Then, you shouldn't need the help function at all:
module.exports = {
methods:{
ajouterCommentaireReponse(commentId){
axios.post('/api/commentsreponse/'+ commentId)
.then(()=>{
// do things
})
},
},
}
</script>

Related

Uncaught (in promise) Error: Request failed with status code 405 VUEJS

so i'm trying to consume an api form laravel via vue.js this is the login page were i did call axios.post :
<template>
<main>
<section class="login-content">
<div class="container h-100">
<div
class="row align-items-center justify-content-center h-100"
>
<div class="col-12">
<div class="row align-items-center">
<div class="col-lg-6">
<h2 class="mb-2">Sign In</h2>
<p>
To Keep connected with us please login with
your personal info.
</p>
<form>
<div class="row">
<div class="col-lg-12">
<div
class="floating-label form-group"
>
<input
class="floating-input form-control"
type="email"
v-model="data.email"
placeholder=" "
/>
<label>Email</label>
</div>
</div>
<div class="col-lg-12">
<div
class="floating-label form-group"
>
<input
class="floating-input form-control"
type="password"
v-model="data.password"
placeholder=" "
/>
<label>Password</label>
</div>
</div>
<div class="col-lg-6">
<div
class="custom-control custom-checkbox mb-3"
>
<input
type="checkbox"
class="custom-control-input"
id="customCheck1"
/>
<label
class="custom-control-label"
for="customCheck1"
>Remember Me</label
>
</div>
</div>
<div class="col-lg-6">
<a
href="auth-recoverpw.html"
class="text-primary float-right"
>Forgot Password?</a
>
</div>
</div>
<button
type="sumbit"
class="btn btn-primary"
#click="login" :disabled="isLogging" :loading="isLogging"
>
Sign In
</button>
<p class="mt-3">
Create an Account
<router-link to="/" exact
>Sign Up</router-link
>
</p>
</form>
</div>
<div class="col-lg-6 mb-lg-0 mb-4 mt-lg-0 mt-4">
<img
src=" asset (html/assets/images/login/01.png)"
class="img-fluid w-80"
alt=""
/>
</div>
</div>
</div>
</div>
</div>
</section>
</main>
</template>
<script>
export default {
data() {
return {
data: {
email: "",
password: ""
},
isLogging: false
};
},
methods: {
async login() {
if (this.data.email == "") return alert("Email is required")
if (this.data.password == "") return alert("Password is required")
/* if(this.data.password.length<6) return this.e ('Incorrect') */
this.isLogging = true
const axios = require('axios')
const headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Method": "POST",
"Content-Type": "application/json",
}
axios.post('http://127.0.0.1:8000/?#/login/',{
email: this.email, password: this.password
}, headers)
.then((response)=>{
const data=response.data;
console.log(data);
})
this.isLogging = false
}
},
mounted() {
console.log("Component mounted.");
}
};
</script>
the step of confirmation : email and password are working well but i got the error when i press the button
and this is the login page as u can see : this is the login page as u can see
i was follwing this tuto but like always i had error unlike the man in the tuto this is the link of the tuto
and this is the route :
Route::post('login', 'App\Http\Controllers\Api\AuthController#login');

How to set if else statement in script

-I wan't to do like this: if(!editMode) show create page else show update page because my create and edit using same form so I combine it.
-I'm learning online tutorial but the tutorial show create and edit seperately.
-Please Helps and Thank/.\
<template>
<div v-if="!edit">
<h1>Create Post</h1>
<form #submit.prevent="addPost">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Title:</label>
<input type="text" class="form-control" v-model="post.title">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Body:</label>
<textarea class="form-control" v-model="post.body" rows="5"></textarea>
</div>
</div>
</div><br />
<div class="form-group">
<button class="btn btn-primary">Create</button>
</div>
</form>
</div>
<div v-else>
<h1>Update Post</h1>
<form #submit.prevent="updatePost">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Title:</label>
<input type="text" class="form-control" v-model="post.title">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Body:</label>
<textarea class="form-control" v-model="post.body" rows="5"></textarea>
</div>
</div>
</div><br />
<div class="form-group">
<button class="btn btn-primary">Update</button>
</div>
</form>
</div>
</template>
<script>
export default {
data(){
return {
edit:false,
post:{}
}
},
},
//this is for create
methods: {
addPost(){
let uri = 'http://localhost:8000/post/create';
this.axios.post(uri, this.post).then((response) => {
this.$router.push({name: 'posts'});
});
},
},
//this is for get data before update
created() {
let uri = `http://localhost:8000/post/edit/${this.$route.params.id}`;
this.axios.get(uri).then((response) => {
this.post = response.data;
});
},
//this is for update post
updatePost() {
let uri = `http://localhost:8000/post/update/${this.$route.params.id}`;
this.axios.post(uri, this.post).then((response) => {
this.$router.push({name: 'posts'});
});
}
</script>
**I also set this in my app.js**
{
name: 'create',
path: '/create',
component: PostForm,
props: {editMode: false}
},
{
name: 'edit',
path: '/edit/:id',
component: PostForm,
props: {editMode: true}
}
My Error--->when I press edit btn show create page and using addPost function.
Result--> how to use if else to solve this.... Sorry I'm rookie in programming.
I believe you can simply have the js figure out the add or update.
<template>
<div>
<h1 v-if="!edit">Create Post</h1>
<h1 v-else>Update Post</h1>
<form #submit.prevent="postSomething">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Title:</label>
<input type="text" class="form-control" v-model="post.title">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Body:</label>
<textarea class="form-control" v-model="post.body" rows="5"></textarea>
</div>
</div>
</div><br />
<div class="form-group">
<button v-if="!edit" class="btn btn-primary">Create</button>
<button v-else class="btn btn-primary">Update</button>
</div>
</form>
</div>
</template>
and the js:
methods: {
postSomething(){
if(!this.edit){
this.addPost()
}else{
this.updatePost()
}
},
addPost(){
console.log('should add')
},
updatePost(){
console.log('should update')
}
}

close parent modal and open child modal on axios success response with laravel vue js

User have to register through two steps. both steps have modal to fill details. for that i have two component ComponentA for first modal and componentB for second modal. Iwant to close first modal on axios success response and open second modal for second registration step.
<template>
<!--sction user-signup 1-->
<div class="signup">
<div class="modal" id="user-signup-1">
<div class="modal-dialog">
<div class="modal-content">
<button type="button" class="close" data-dismiss="modal">×</button>
<!-- Modal body -->
<div class="modal-body text-center" style="background:url(images/user-signup-bg.jpg) no-repeat left top; ">
<h2>SIGN UP</h2>
<h5 class="setp-tag">Step 1 of 2</h5>
<h6>Registered users have access to all MoneyBoy features. This is not a Moneyboy Profile.<br>
If you’d like to create a Moneyboy Profile please click here.</h6>
<form class="user-signup-form" action="./api/user/signup" method="POSt" #submit.prevent="addUser()">
<div class="form-group">
<label>Username</label>
<input type="text" name="username" v-model="username" placeholder="mohamed-ali" class="span3 form-control">
<span v-if="hidespan">5 - 20 characters. Letters A-Z and numbers 0-9 only. No spaces.
E.g. MikeMuscleNYC.</span>
<span v-if="errorinusername"> {{ errorinusername }}</span>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" v-model="email" placeholder="mohamed-ali#gmail.com" class="span3 form-control">
<span v-if="errorinemail"> {{ errorinemail }}</span>
</div>
<div class="form-group">
<label>Create a password</label>
<input type="password" name="password" v-model="password" placeholder="**********" class="span3 form-control">
<span v-if="errorinusername"> {{ errorinpassword}}</span>
</div>
<div class="form-group turms">
<input name="" type="checkbox" value="1" v-model="checked" id="terms"><label for="terms">I am over 18 and agree to the
Terms & Conditions</label>
<!--<label><input type="checkbox" name="terms">I am over 18 and agree to the Terms & Conditions.</label>-->
<input type="submit" :disabled="!checked" value="SIGN UP NOW" class="btn btn-primary w-100">
</div>
<div class="form-group">
<p>If you’d like to create a Moneyboy Profile click here.</p>
</div>
<div class="clearfix"></div>
</form>
</div>
</div>
</div>
</div>
<usersignup2component #recordadded="openusersignup2modal()"></usersignup2component>
</div>
<!--sction user-signup 1-->
</template>
<!--sript -->
<script>
Vue.component('usersignup2component', require('./UserSignup2Component.vue').default);
export default {
data(){
return {
username: '',
email:'',
password:'',
checked: false,
errorinusername: '',
errorinemail: '',
errorinpassword: '',
hidespan: true,
}
},
methods:{
addUser(){
axios.post('./api/user/signup', {
username:this.username,
email:this.email,
password:this.password
})
.then((response) =>{
this.$emit('recordadded');
})
.catch((error) => {
console.log(error.response);
this.hidespan = false;
this.errorinusername = error.response.data.errors.username;
this.errorinemail = error.response.data.errors.email;
this.errorinpassword = error.response.data.errors.password;
});
},
openusersignup2modal(){
console.log('okkkkkkkkkkkkkk');
}
},
mounted() {
console.log('UserSignUp1Component mounted.')
}
}
</script>
What I am doing wrong. I tried to console.log() on openusersignup2modal method to see, if it this function ever called or not. Found no activity on openusersignup2modal()

Reset input on click, vue

I would like to have my text fields empty when I click "add task" button. How could I achieve that?
<template>
<div class="col-md-6" >
<div class="card bg-light mt-4">
<div class="card-header">Task Form</div>
<div class="card-body">
<form action="./api/word" method="post" #submit.prevent="addTask()">
<div class="form-group">
<input type="text" name="title" v-model="title" placeholder="Local word" class="form-control">
</div>
<div class="form-group">
<input type="text" name="second_title" v-model="second_title" placeholder="Foreign word" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="Add Task" class="btn btn-info">
</div>
</form>
</div>
</div>
</div>
</template>
export default {
data() {
return {
title: '',
second_title: ''
}
},
mounted() {
console.log('Component mounted.')
},
methods: {
addTask() {
Event.$emit('taskCreated', {
title: this.title,
second_title: this.second_title
});
axios.post('./api/word', {
title: this.title,
second_title: this.second_title,
})
this.title = '';
this.second_title = '';
}
It's very simple, in the addTask() just add event as parameter and in the end of the function you write: event.target.reset();
Code:
<template>
<div class="col-md-6" >
<div class="card bg-light mt-4">
<div class="card-header">Task Form</div>
<div class="card-body">
<form action="./api/word" method="post" #submit.prevent="addTask">
<div class="form-group">
<input type="text" name="title" v-model="title" placeholder="Local word" class="form-control">
</div>
<div class="form-group">
<input type="text" name="second_title" v-model="second_title" placeholder="Foreign word" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="Add Task" class="btn btn-info">
</div>
</form>
</div>
</div>
</div>
</template>
And there:
export default {
data() {
return {
title: '',
second_title: ''
}
},
mounted() {
console.log('Component mounted.')
},
methods: {
addTask(event) {
Event.$emit('taskCreated', {
title: this.title,
second_title: this.second_title
});
axios.post('./api/word', {
title: this.title,
second_title: this.second_title,
})
this.title = '';
this.second_title = '';
event.target.reset();
}
Hope it works for you ; )

cannot insert data into vue select sent from laravel

This is the vuejs component for editing song info. the problem here is with tags.I cannot show the tags of the song in vue select for editing.
<template>
<div>
<a data-toggle="modal" :data-target="'#EditModal'+ modalid" #click="select(song)"><span title="edit" class="glyphicon glyphicon-pencil" ></span></a>
<a class=""><span title="delete" class="glyphicon glyphicon-trash"></span></a>
<!-- Modal for editing song tracks-->
<div class="modal fade" :id="'EditModal'+ modalid" tabindex="-1" role="dialog" aria-labelledby="EditModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="EditModalLabel">Edit Song</h5>
<button type="button" class="close" ref="closemodal" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form ref="uploadform">
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="col-md-5">
<button type="button" #click="browseImage" class="btn btn-md btn-default">Choose image:</button>
<div id="image_previews">
<img ref='image' class="" v-bind:src="image" width="200px" height="200px" >
<input class="form-control-file" ref="imageinput" type="file" name="feature_image" #change="showImage($event)">
</div>
</div>
<div class="col-md-7">
<div class="form-group">
<label for="title">Song Title:</label>
<input type="text" v-model="esong.title" class="form-control" required maxlength="255">
</div>
<div class="form-group">
<label for="genre"> Genre (tag atleast one) </label>
<v-select :placeholder="'choose tag'" v-model="tagids" label="name" multiple :options="tags"></v-select>
</div>
<div class="form-group">
<label for="upload_type">Song Upload Type</label>
<select name="upload_type" v-model="esong.upload_type" class="form-control">
<option value="public">public( free )</option>
<option value="private">private( for sale )</option>
</select>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Description:</label>
<textarea class="form-control" id="message-text" v-model="esong.song_description"></textarea>
</div>
<div class="form-group" v-if="private">
<label for="upload_type">Song price</label>
<input type="text" v-model="esong.amount" class="form-control" required maxlength="255">
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" #click="edit">Save</button>
</div>
</div>
</div>
</div><!-- end of modal -->
</div>
</template>
<script>
import vSelect from 'vue-select'
export default {
props: ['song','modalid','index','tags'],
components: {vSelect},
mounted() {
},
watch: {
tagids() {
console.log('changed tagids value');
// this.value = this.tagsid;
}
},
computed: {
private() {
if(this.esong.upload_type == 'private') {
return true;
}
return false;
},
},
methods: {
select(song) {
console.log(song.title);
this.getTagIds(song);
},
edit() {
let formData = new FormData();
formData.append('title', this.esong.title);
formData.append('img', this.esong.img);
formData.append('description', this.esong.song_description);
formData.append('upload_type', this.esong.upload_type);
formData.append('amount', this.esong.amount);
formData.append('tags', JSON.stringify(this.tagids));
formData.append('_method', 'PUT');
axios.post('/artist/songs/' + this.esong.id, formData,{
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response =>{
this.$refs.closemodal.click();
toastr.success('successfully edited song.');
this.$emit('update', {song:this.esong,index:this.index});
}).catch(error => {
console.log(error);
});
},
getTagIds(song) {
axios.post('/gettagids', song ).then(response =>{
this.tagids = response.data;
}).catch(error =>{
console.log(error);
});
},
browseImage() {
this.$refs.imageinput.click();
},
showImage(event) {
this.esong.img = event.target.files[0];
this.image = URL.createObjectURL(event.target.files[0]);
}
},
data() {
return {
esong: this.song,
tagids: {id:'', name:'', label:''},
name:'name',
image:this.song.image
}
}
}
</script>
<style scoped>
input[type="file"] {
display: none;
}
#image_previews {
border-radius: 5px;background-color: whitesmoke; width: 200px; height: 200px;
}
.btn{
border-radius: 0px;
}
</style>
here I cannot get the selected value that was inserted in my table. I wanted to show the tagged values for a song. I am able to get all object of tagged songs from axios post request but v-select doesn't shows the selected value retrieved from a table.
the object received from laravel is similar to the object provided in options which work well with v-select..but it doesn't show the same structure object provided to v-model..or should I provide other props. the document for vue select has not mentioned any of these things

Resources