Undefined variable in laravel with vue using vform package - javascript

I dont know whats happening with my code in the controller. I just want to send an email based on the select option from my vue component. It just says undefined variable request. Im using vform package from vue. But in my controller I already defined the request variable with with the id of the select option from my vue component. But when I put some static email, it can send email and it worked. Can someone know what is the solution? Thanks.
Error in preview in network tab
{message: "Undefined variable: request", exception: "ErrorException",…}
exception: "ErrorException"
file: "C:\Users\bustillo-ronald\Desktop\Laravel-SPA\app\Http\Controllers\API\UserController.php"
line: 196
message: "Undefined variable: request"
trace: [,…]
My controller
public function sendEmail(Request $request){
$beautymail = app()->make(\Snowfire\Beautymail\Beautymail::class);
$beautymail->send('emails.welcome', [], function($message)
{
$message
->from('test#gmail.com')
//->to('sampleemail#gmail.com')//this is working with static data
->to($request->email)
->subject('Welcome!');
});
}
My vue component with vform
<form #submit.prevent="sendEmail()">
<div class="modal-body">
<div class="form-group">
<label>Users Lsit</label>
<select v-model="form.email" name="email" id="email" class="form-control" :class="{ 'is-invalid': form.errors.has('email') }">
<option v-for="user in users.data" :key="user.id" >{{user.email}}</option>
</select>
<has-error :form="form" field="type"></has-error>
</div>
<div class="form-group">
<label>Message</label>
<textarea v-model="form.message" name="message" placeholder="Message" class="form-control" :class="{ 'is-invalid': form.errors.has('message') }"></textarea>
<has-error :form="form" field="message"></has-error>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Send Email</button>
</div>
</form>
The script.
export default {
data() {
return {
form: new Form({
id:'',
email: '',
message: ''
}),
users: []
}
},
methods: {
getUsers() {
axios.get('api/user')
.then((res) => {
this.users = res.data
})
},
sendEmail(){
this.form.post('api/sendemail')
.then(()=>{
$('#exampleModal').modal('hide');
$(".modal-backdrop").remove();
swal.fire("Email sent!", "", "success");
})
.catch((e)=>{
console.log(e)
})
}
},
created() {
this.getUsers();
console.log('Component mounted.')
}
}
Vue devtools

you are not passing the $request variable inside the closure.
public function sendEmail(Request $request){
$beautymail = app()->make(\Snowfire\Beautymail\Beautymail::class);
$beautymail->send('emails.welcome', [], function($message) use($request) // add use($request)
{
$message
->from('test#gmail.com')
//->to('sampleemail#gmail.com')//this is working with static data
->to($request->email)
->subject('Welcome!');
});
}

Related

I am attempting to create a firebase login page on a web app, however when I attempt to login, nothing happens [duplicate]

I'm trying to get the sign in part working on my webapp but it's not working properly.
Whenever I press the login button the page either refreshes and the url gets updated with the credentials and stays at the same page OR the router gets pushed and goes to the 'homepage' without logging the user in.
I also followed this guide for reference: https://blog.logrocket.com/vue-firebase-authentication/
What's weird is that the sign up part is working just fine.
SignIn.vue
<div class="card-body">
<form>
<!-- email -->
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input id="email" type="email" class="form-control" name="email" placeholder="e-mail" value required autofocus v-model="form.email" />
</div>
<!-- password -->
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input id="password" type="password" class="form-control" name="password" placeholder="password" required v-model="form.password" />
</div>
<!-- error -->
<div v-if="error" class="alert alert-danger animated shake">{{ error }}</div>
<br />
<!-- login -->
<div class="form-group d-flex justify-content-between">
<div class="row align-items-center remember"><input type="checkbox" v-model="form.rememberMe" />Remember Me</div>
<input type="submit" #click="submit" value="Login" class="btn float-right login_btn" />
</div>
</form>
</div>
Script in SignIn.vue
<script>
import firebase from 'firebase';
export default {
data() {
return {
form: {
email: '',
password: '',
rememberMe: false
},
error: null
};
},
methods: {
submit() {
firebase
.auth()
.signInWithEmailAndPassword(this.form.email, this.form.password)
.catch(err => {
this.error = err.message;
})
.then(data => {
this.$router.push({ name: 'home' });
});
}
}
};
</script>
Store.js
import Vue from 'vue';
import Vuex from 'vuex';
import profile from './modules/profile';
import authenticate from './modules/authenticate';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
profile,
authenticate
}
});
Authenticate.js in store
const state = {
user: {
loggedIn: false,
data: null
}
};
const getters = {
user(state) {
return state.user;
}
};
const mutations = {
SET_LOGGED_IN(state, value) {
state.user.loggedIn = value;
},
SET_USER(state, data) {
state.user.data = data;
}
};
const actions = {
fetchUser({ commit }, user) {
commit('SET_LOGGED_IN', user !== null);
if (user) {
commit('SET_USER', {
displayName: user.displayName,
email: user.email
});
} else {
commit('SET_USER', null);
}
}
};
export default {
state,
mutations,
actions,
getters
};
It is probably because you assign the submit type to your button, your form is submitted before the Firebase method is triggered.
You should change the button code from
<input type="submit" #click="submit" value="Login" class="btn float-right login_btn" />
to
<input type="button" #click="submit" value="Login" class="btn float-right login_btn" />
See the W3 specification for more detail on button types.

How to catch the invalid response from the backend and display that error as alert in UI page in vue.js?

i am developing one registration page and it's connected with the backend API by using axios package it's working fine ,if i enter invalid credentials or already existing emailID it's showing me user registered successfully as alert and from the response i am getting [invalid response 422]1(status as 422 when i am giving existing user credentials and at that time also it's showing user registered successfully as alert [like this it's showing]2), i want to catch the response or status from the backend and placed inside catch block which is present inside the Register.vue component and display as a alert message(for invalid response also), please help me to fix this issue on valid response only it's should display success msg and if it's invalid means it's should display the error as alert based on response msg (if response==422 means then i want to print invalid as alert)
Register.vue
<template>
<div class="main">
<div class="container">
<img src="../assets/sideImg.png" alt="notFound" />
<p>Online Book Shopping</p>
<div class="box">
<div class="headings">
<h5 class="signin">Login</h5>
<h5 class="signup">signup</h5>
</div>
<form ref="myForm" #submit.prevent="handlesubmit">
<div class="fullname">
<p>FullName</p>
<input type="name" class="namebox" required v-model="fullName" autocomplete="off" pattern="[A-Za-z]{3,12}">
</div>
<div class="username">
<p>EmailID</p>
<input type="email" class="emailbox" required v-model="emailID" pattern="^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$">
</div>
<div class="pass">
<p>Password</p>
<input :type="password_type" class="password" id="passField" v-model="password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{6,}$" required>
<i class="bi bi-eye-slash" id="togglePassword" #click="togglePassword();"></i>
</div>
<div class="mobile">
<p>MobileNumber</p>
<input type="tel" class="telephone" v-model="mobile" pattern="^\d{10}$" required>
</div>
<button class="btn-section" type="submit">Signup</button>
</form>
</div>
</div>
</div>
</template>
<script>
import service from '../service/User'
export default {
name: 'Register',
data() {
return {
fullName: '',
emailID: '',
password: '',
mobile: '',
password_type: "password",
}
},
methods: {
togglePassword() {
this.password_type = this.password_type === 'password' ? 'text' : 'password'
document.getElementById('passField').style.margin='0px 0px 0px 69px';
document.getElementById('passField').style.width="252px";
document.getElementById('passField').style.height="35px";
document.getElementById('passField').style.background="$pale_white 0% 0% no-repeat padding-box";
},
handlesubmit() {
let userData = {
fullName: this.fullName,
emailID: this.emailID,
password: this.password,
mobile: this.mobile
}
service.userRegister(userData).then(response => {
alert("user registered successfully");
this.$refs.myForm.reset();
return response;
}).catch(error => {
if(error.response==422){alert("internal server issue");}
return error;
})
}
}
}
</script>
<style lang="scss" scoped>
#import "#/styles/Register.scss";
</style>
axios.js[responsible for postData]
import axios from 'axios'
axios.defaults.baseURL=process.env.VUE_APP_AXIOS_URL
axios.defaults.headers.common['Authorization']='Bearer'+ localStorage.getItem('token');
export default class AxiosService{
postData(url,data){
return axios.post(url,data).then(response =>{
return response;
}).catch(error=>{
return error;
})
}
}
User.js[responsible for hitting backend api]
import AxiosService from '../service/axios';
const axios=new AxiosService()
export default{
userRegister(data){
return axios.postData("/register",data);
},
}

why is this error coming Uncaught (in promise) TypeError: Cannot read property 'created' of undefined in vue.js

this is the code I've implemented in vue.js
I was trying to add a new employee to the firebase database.
the code was working until I wrote the methods and initialized the data section
when I tried going back steps where the code was running it was still giving runtime error
<template>
<div class="container-fluid">
<center><h1>New Employee</h1></center>
<form #submit.prevent="adds" class="form">
<label>Enter Name</label>
<input type="text" class="form-control" v-modle="name">
<label>Enter Employee ID</label>
<input type="text" class="form-control" v-modle="emp_id">
<label>Enter Department</label>
<input type="text" class="form-control" v-modle="dep">
<label>Enter Position</label>
<input type="text" class="form-control" v-modle="position" >
<router-link to="/" class="btn btn-danger btn-lg">Cancel</router-link>
<button type="submit" class="btn btn-outline-success btn-lg">Submit</button>
</form>
</div>
</template>
<script>
import db from '../components/firebaseinit.js'
export default {
name:"newEmployee",
data(){
return{
name: null,
emp_id: null,
dep: null,
position: null
}
},
methods:{
adds(){
db.collection('employee').add({
emp_id: parseInt(this.emp_id),
name: this.name,
dep: this.dep,
position: this.position
}).then(this.router.push("/")).catch(err => console.log(err))
}
}
}
</script>
I found the problem with my code at line 42
then(this.router.push("/")).catch(err => console.log(err))
The right way to call router is by $ the code would be replaced by
then(() => this.$router.push("/")).catch(err => console.log(err))

show message after submit data using laravel and vue.js

good day;
i new in laravel and vue.js when i submit form if i have problem in validate one of input it show correctly like The Brand Name field is required. but my real problem is when submitted form successfully when i show response message that i get from controller **i get only one capital** **litter of message appear** only like ***Y*** like "Your Data Added Successfully" but i get the first litter isY` like attached photo that appear how can i solve this problem
thanks
here is my controller
<?php
namespace App\Http\Controllers;
use App\PhoneBook;
use Illuminate\Http\Request;
use Validator;
class PhoneBookController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
return view('phonebook');
}
}
public function add(Request $request)
{
//prepare data for validation
$validationarray=Validator::make($request->all(),
[
'name' => 'required',
'phone' => 'required|min:2|required',
'email' => 'required',
]
,[],[
"name"=>"Brand Name",
'phone' => 'phone',
'email' => 'Email',
]);
if($validationarray->fails())
{
foreach ($validationarray ->messages()->getMessages() as $field_name =>$message):
$response['message']=$message;
endforeach;
$response['status']="failed";
return response()->json($response);
}
// start pass data to model
$branddata=array(
'name' =>$request->name,
'phone' =>$request->phone,
'email' =>$request->email,
);
// start add data
$add=PhoneBook::create($branddata)->id;
if(false !=$add)
{
return response(['status'=>'success',"message"=>"Your Data Added Successfully"]);
}else{
return response(['status'=>'failed',"message"=>"Error Adding data please try again !!"]);
}
}
then my route is
Route::post('phonebook/add',"PhoneBookController#add")->name("cart.deleteProductFromCart");
my view code template
<template>
<div>
<div class="modal fade" id="addData" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New message</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<span v-if="list.status=='success'" >Record submitted successfully!</span>
<div v-model="list.message" >{{list.message?list.message[0]:''}}</div>
<div class="form-group">
<label for="exampleInputEmail1">Brand Name</label>
<input type="text" name="name" v-model="list.name" class="form-control" id="exampleInputEmail1" placeholder="Example : Kia - Renault">
<p class="help-block">Example : Kia - Renault</p>
</div>
<div class="form-group">
<label class="col-form-label">phone:</label>
<input type="text" name="phone" v-model="list.phone" class="form-control" id="reckipient-name">
<p class="help-block">Example : Kia - Renault</p>
</div>
<div class="form-group">
<label class="col-form-label">email:</label>
<input type="text" class="form-control" v-model="list.email" name="email" id="recikpient-name">
<p class="help-block">Example : Kia - Renault</p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" #click="save">Send message</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "addData",
data: function () {
return {
list: {
name: '',
phone: '',
email: '',
message:'',
},
}
},
methods: {
save: function () {
axios.post('/phonebook/add',this.$data.list)
.then((response) => this.list.message=response.data.message)
.catch((error) => this.list.message=error.response.data.message)
}
}
}
</script>
<style scoped>
</style>
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/sZpDS.png
It's good to pass response as JSON Format
YourXYZController.php
....
$data = new stdClass;
$data->status = "success";
$data->message = "your message";
return response(json_encode($data));
in Vuejs
axios.post('YourXYZController URL', params)
.then(response => {
console.log(response)
})
.catch(error => {
console.log(response)
})
})
And also it's best practice to check request and response in network tab of browser.

Show bootstrap alert with condition (Vue.js): how can I access this variable in order to change its value?

First of all I would like to apologize if the answer to my question is obvious, however since I'm still pretty new to Vue.js, I'm getting really stuck here and I need help.
I got an authentication system and if the user wants to register without putting in an username, I would like to show an bootstrap alert. The code looks like this right now:
<template>
<div class="container">
<div class="row">
<div class="col-md-6 mt-5 mx-auto">
<form v-on:submit.prevent="register">
<h1 class="h3 mb-3 font-weight-normal">Register</h1>
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
v-model="username"
class="form-control"
name="username"
placeholder="Please choose your username"
>
</div>
<div class="form-group">
<label for="email">Email Address</label>
<input
type="email"
v-model="email"
class="form-control"
name="email"
placeholder="Please enter your email address"
>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
type="password"
v-model="password"
class="form-control"
name="password"
placeholder="Please choose your password"
>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>
</form>
<div>
<b-alert variant="success" show>Example alert</b-alert>
</div>
<div>
<b-alert variant="danger" :show="showAlert">Example Alert!</b-alert>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
import router from "../router";
export default {
data() {
return {
username: "",
email: "",
password: "",
showAlert: false };
},
methods: {
register() {
axios
.post("/user/register", {
username: this.username,
email: this.email,
password: this.password
})
.then(res => {
if (!res.data.username) {
// show an alert, I would like to do something similar to "showAlert = true;"
} else {
// redirect to login
}
})
.catch(err => {
console.log(err);
});
}
}
};
</script>
<style scoped>
#import "../assets/css/reglog.css";
#import "../assets/css/modal.css";
</style>
However I'm not sure how to access the showAlert variable neither how to change its value in the if-statement. The only thing that I know here is that if I change the showAlert manually in the code (line 9 counting from the script tag) from false to true, the page does react and shows the alert when wanted.
I'm sorry if you need more information or if something is unclear, I'm a bit tired and stuck with this for some hours, not gonna lie.
You can access showAlert variable following: this.showAlert = true
.then(res => {
if (!res.data.username) {
this.showAlert = true; // update showAlert
} else {
// redirect to login
}
})

Categories