adjust the url when fetching data in vue.js component - laravel

So i am trying to fetch data in my vue component as you can see below. But because iam reqesting the fetch from my blade view in public/manage-users-projects the url becomes
http://localhost:8080/ProjsiteWebApp/app/public/manage-users-projects/get-projects-json
but i want to fetch data from this url
http://localhost:8080/ProjsiteWebApp/app/public/get-projects-json
So i can i sort of return one route and execute from the public folder?
export default {
created(){
this.fetchProjects();
},
methods:{
fetchProjects() {
fetch('get-projects-json')
.then(res => res.json())
.then(res => {
console.log(res.data);
})
}
}
};
Route::get('get-projects-json', 'ProjectsController#getProjectsJson');

You can pass the route as props to the component inside the blade file.
Inside the view:
<component get-projects-json="{{ url('get-projects-json') }}"></component>
Inside the vue component:
<script>
export default {
props: ['getProjectsJson'],
}
</script>
Then you can access the route inside the component like so:
export default {
created(){
this.fetchProjects();
},
methods:{
fetchProjects() {
fetch(this.getProjectsJson)
.then(res => res.json())
.then(res => {
console.log(res.data);
})
}
}
};
You can learn more about props here: https://v2.vuejs.org/v2/guide/components-props.html

Related

axios call return same value after props value changed

My code looks like this
child component.vue
<script>
export default {
props: ['Pconvs_id'],
data(){
return{
user : '',
messages:[],
newMessage : '',
convs_id: '',
}
},
created(){
this.convs_id = this.Pconvs_id;
this.fetchMessages();
},
methods:
{
fetchMessages()
{
console.log(this.convs_id);
axios.get('messages',{cons_id: this.convs_id}).then(response=> {
this.messages = response.data;
});
axios.get('authuser').then(response=>{
this.user = response.data;
});
},
},
watch: {
// whenever convs_id changes, this function will run
Pconvs_id: function (newConvs_id, oldConvs_id) {
this.convs_id = newConvs_id;
this.fetchMessages();
}},}
</script>
parent component.vue
<Message :Pconvs_id="convs_id"/>
my problem is that even when the convs_id changed fetchmessage() return same data what did i do wrong
axios call handler
public function fetchmessages(Request $cons_id)
{
return Message::where([
['cons_id' , $cons_id],
])->with('user')->get();
}
Elequent relationship
message model beongsTo user and User hasMany message
I think your backend handler receives an instance of Illuminate\Http\Request
so to get the cons_ids you should to something like
public function fetchmessages(Request $request)
{
// Get the cons_id from the request object
$cons_id = $request->get('cons_id');
// Cleaned up your "where" query
return Message::where('cons_id', $cons_id)->with('user')->get();
}

Redirect in inertia js and jetstream in javascript code

I want to be redirected to single question page after creation of question
summitQuestion(){
this.question_button = true
axios.post('/api/question/ask', {
'title' : this.question.title,
'body' : this.question.body,
'tags' : this.tags,
'user_id' : this.$page.props.user.id
}).then(response=>{
this.question_button = false
console.log(response.data)
}).catch(error=>{
this.question_button = false
console.log(error.response.data.errors)
if(error.response.data.errors){
this.title_errors = error.response.data.errors.title
this.body_errors = error.response.data.errors.body
}
})
},
I have this function I want after the success of the request to redirect I a spa way without page reloading to question single page I am using inertia js and jetstream my laravel router is below
Route::middleware(['auth:sanctum', 'verified'])->get('/question/{question}', 'App\Http\Controllers\QuestionController#show')->name('question-single');
Simply use the visit method on the inertia like shown below.
this.$inertia.visit(route('question-single'), { method: 'get' });
If you got everything correct from your code above remaining the redirection without your page reloading, then I guess the modification of your code will be the sample as folows;
summitQuestion(){
this.question_button = true
axios.post('/api/question/ask', {
'title' : this.question.title,
'body' : this.question.body,
'tags' : this.tags,
'user_id' : this.$page.props.user.id
}).then(response=>{
this.question_button = false
// console.log(response.data)
this.$inertia.visit(route('question-single'), { method: 'get', data: response.data });
}).catch(error=>{
this.question_button = false
console.log(error.response.data.errors)
if(error.response.data.errors){
this.title_errors = error.response.data.errors.title
this.body_errors = error.response.data.errors.body
}
})
},
You can make reference to this by visiting The Official Inertiajs Website
If you are using Inertia, you are supposed to create a form with v-model linked to fields. Add to that a button of type submit that call your method (see below the method example).
<form #submit.prevent="submitQuestion">
<input type="text" v-model="form.title">
<button type="submit"></button>
</form>
<script>
export default {
data() {
return {
form: this.$inertia.form({
title: this.question.title,
body: this.question.body,
tags: this.tags,
user_id: this.$page.props.user.id,
}, {
bag: 'default',
}),
}
},
methods: {
summitQuestion: function() {
this.form.post('/api/question/ask');
},
}
};
</script>
The redirection can be done directly on your controller method.
class QuestionController extends Controller
{
public function create(Request $request) {
// Create your question
return redirect()->route('your.route');
}
}

Input vue Js foreign key

I am first using input in vue js . this input have structure like this
induk_id:'',
nama_barang:'',
qtt:'',
satuan:'',
harga:'',
harga_total:'',
keterangan:'',
status:'Aktif',
this induk_id is foreign key on another table , but i dont know how to pass this induk_id on this vue .
i use laravel vue js and this is controller and route
public function input_detail($id)
{
$pencairan = IndukPencairan::findOrFail($id);
if (!$pencairan)
abort(404);
return view('pengadaan.inputdetail',['pencairan' => $pencairan]);
}
this controller on laravel blade i can pass like $pencairan->id for this induk_id , but how i can pass this on vue ?
and its my route
Route::get('input_detail/{id}', 'PengadaanController#input_detail')->name('input_detail');
and its my export default
export default {
data(){
return{
count: 0,
userData:[{
induk_id:'',
nama_barang:'',
qtt:'',
satuan:'',
harga:'',
harga_total:'',
keterangan:'',
status:'Aktif',
}],
}
},
components:{
},
methods:{
submit() {
this.errors = {};
axios.post('/pengadaan/store_induk_pencairan', this.userData).then(response => {
window.location = response.data.redirect;
}).catch(error => {
if (error.response.status === 422) {
this.errors = error.response.data.errors || {};
}
});
},
AddField: function () {
this.userData.push({ induk_id: '',nama_barang: '' ,qtt: '' ,satuan: '',harga: '' ,harga_total: '',
keterangan: '' ,status: 'Aktif',
});
}
},
my question is how i retrieve induk_id in vue js ?
Your question is quite unclear, it needs a better explanation. Do you mean how to pass the 'induk_id' on axios post request. If that's the case, it's quite easy.
Call the submit function on vue passing the induk_id paramater whenever you want to action to be performed.
<button #click="submit(induk_id)"> Submit </button>
Then in methods, accept the parameter and concat using template literals ``
submit(id) {
this.errors = {};
axios.post(`/pengadaan/store_induk_pencairan/${id}`, this.userData).then(response => {
window.location = response.data.redirect;
}).catch(error => {
if (error.response.status === 422) {
this.errors = error.response.data.errors || {};
}
});
}
That's it, if its something you are looking for. But I'm not sure if you were asking about this, just my assumptions. Feel free to add more details.
<template>
<div>{{ response_data }}</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
formdata: {
induk_id: "",
nama_barang: "",
qtt: "",
satuan: "",
harga: "",
harga_total: "",
keterangan: "",
status: "Aktif",
},
response_data: null,
};
},
methods: {
submit() {
axios
.get(`input_detail/${this.formdata.induk_id}`)
.then((response) => {
this.response_data = response.data;
})
.catch((error) => {
console.log(error);
});
},
},
};
</script>
<style lang="scss" scoped></style>

Am i missing something, this.form.fill() doesn't seems to work for me

My UserController Function:
public function profile()
{
return auth('api')->user();
}
i'm working on project that frontend with vue and backend with laravel.
My Vue.js Code:
import Form from 'vform';
export default {
data () {
return {
form: new Form({
id:'',
name: '',
email: '',
password: '',
type:'',
bio:'',
photo:''
})
}
},
mounted() {
console.log('Component mounted.')
},
created(){
axios.get("api/profile")
.then( ({data}) => (this.form.fill(data)))
}
}
i try to show data in form, but when i call this function it not return the data. what i am doing wrong? i know there is problem with this function this.form.fill(data) but i don't know what actual the problem is.

How to retrieve User name in Vue component with Laravel

I have a vue component that will send a message and I want to send the logged in user name. I'm using laravel 5.5
methods:{
sendMessage(){
this.$emit('messagesent', {
message:this.messageText,
user: {
name : {{Auth()::user()->name}} //Here is where it should be
}
});
this.messageText = '';
}
}
I already tried using
{{Auth()::user()->name}}
Auth()::user()->name
Both give errors. How can I retrieve the name?
Depend on your approach, this can be achieve in different ways
1. Pass in the username from the view
<send-message user={{ $user->username }} ></send-message>
then inside your vuejs component
export default {
props: ['user'],
data(){
return {
user: ''
}
},
methods: {
sendMessage(){
var user = JSON.parse(this.user)
//do you thing here
}
},
}
2. Bind the user information to window object on your page header
<script>
window.user = {!! json_encode([
'user' => $user->username,
]) !!};
</script>

Resources