I am follow this Link for a inertiaJS tutorial. BTW I'm using laravel 8
I have this image below from my webpage. I don't know why I don't have a page>errors in picture given. Is there any other way to validate a form other than the link that I provided?.
I commented out the page.error in my HTML because it causes me an error Error in render: "TypeError: Cannot read property 'email' of undefined" because of my Page.Error is an empty object.
Update : Code for my controller
Script Code
<script>
import Layout from "../../Shared/Layout";
export default {
components: {
Layout,
},
data() {
return {
lead: {
name: "",
email: "",
phone: "",
dob: "",
interested_package: "",
},
};
},
methods: {
async handleSubmit() {
let res = await this.$inertia.post("/leads/save", this.lead);
},
},
};
</script>
App Service Provider
public function boot()
{
//
Schema::defaultStringLength(255);
Inertia::share([
'errors' => function () {
return Session::get('errors')
? Session::get('errors')->getBag('default')->getMessage()
: (object)[];
}
]);
Inertia::share('flash', function () {
return [
'message' => Session::get('message'),
'success' => Session::get('success'),
'error' => Session::get('error'),
];
});
}
To access the email error, context needs to be added via the this keyword ie. this.$page.props.errors.email.
Hey i think you are not sharing error bag in Controller that is why is empty ,to solve this, go to your AppServiceProvider
and add this code.
Inertia::share([
'errors' => function () {
return Session::get('errors')
? Session::get('errors')->getBag('default')->getMessages()
: (object) [];
},
]);
Related
I want to do paypal integration in Laravel. I have use composer require srmklive/paypal to install the srmklive/paypal package for my project. I get 404 error when I want to press the PayPal button. The popup paypal login tab will missing. Then I inspect the network I get the error like image given.
Here is my code:
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);
$plan = $provider->createOrder([
"intent" => "CAPTURE",
"purchase_units" => [
[
"amount" => [
"currency_code" => "USD",
"value" => "30"
],
"description" => "Item 1"
]
]
]);
return response()->json($plan);
}
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);
}
}
Here is the code from blade file
paypal.Buttons({
createOrder: function(data, actions) {
return fetch('api/paypal/order/create/', {
method: 'post',
body:JSON.stringify({
"value":30
})
}).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(); // Recoverable state, per:
}
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
return alert(msg);
}
});
}
}).render('#paypal-button-container');
The error show like image given.
Does anyone know how to solve it?
Does the route api/paypal/order/create/ exist on your server? From the error message, it's returning a 404.
The route must exist (no 404) and successfully output a JSON response with an id obtained from the PayPal API.
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');
}
}
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>
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.
I am trying to send some data from my vue component to database using a laravel controller. To avoid blank input error, I already made all my table columns nullable except the ID. Still when I am trying to send the data using post method, i am getting error 500.
Here is my vue method:
addRecord(){
fetch('api/video_call', {
method: 'post',
body: JSON.stringify(this.call_detail),
headers: {
'content-type': 'application/json'
}
})
.then(res => res.json())
.then( data=> {
this.call_detail.receiver_caller_id = '';
this.call_detail.sender_caller_id = '';
this.call_detail.receiver_id= '';
this.call_detail.sender_id= '';
this.call_detail.call_received='';
alert('Test Done');
this.fetchCallDetail();
})
.catch(err => console.log(err));
}
}
here is the data that I am returning from vue:
data(){
return {
users: [],
call_details: [],
call_detail: {
id: '',
receiver_caller_id: '',
sender_caller_id: '',
receiver_id: '',
sender_id: '',
call_received: ''
},
call_detail_id: '',
pagination: {},
call_allowed: false
}
}
Here is my route in api.php
Route::post('video_call', 'VideoCallController#store');
And finally here is the store function in controller:
public function store(Request $request)
{
$record = $request->isMethod('put')?VideoCall::findOrFail($request->call_detail_id):new VideoCall;
$record->id= $request->input('call_detail_id');
$record->receiver_id= $request->input('receiver_id');
$record->sender_id= $request->input('sender_id');
$record->sender_call_id= $request->input('sender_call_id');
$record->receiver_call_id= $request->input('receiver_call_id');
$record->call_recieved=$request->input('call_received');
if($record->save())
{
return new VideoCallResource($record);
}
}
I used this methods in my previous apps to send data from vue to database and it worked just fine. In this app it is returning error.