Register component doesn't insert data. Throws new MethodNotAllowedHttpException($others); - laravel

I'm trying to post user register data to my db using axios.post from Register.vue component. but this gives me an error. I don't know if the error is on the form or on the inputs.
This is my Register.vue
<template>
<div class="login-wrapper border border-light">
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal">
<h2 class="form-signin-heading">Please sign in</h2>
<div class="form-group">
<label for="usuario" class="sr-only">Username</label>
<input v-model="usuario" type="usuario" id="inputEmail" class="form-control" placeholder="Username" required autofocus>
<label for="inputEmail" class="sr-only">Email </label>
<input v-model="email" type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input v-model="password" type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<button class="btn btn-primary" #click="registrarUsuario()">Register</button>
</div>
</form>
</div>
</template>
<script>
export default {
data () {
return {
usuario: '',
email: '',
password: '',
errorPersona : 0,
errorMostrarMsjPersona : [],
}
},
methods: {
registrarUsuario(){
console.log(this.email);
if (this.validarUsuario()){
return;
}
let me = this;
axios.post('/user/registrar',{
'email' : this.email,
'usuario': this.usuario,
'password': this.password
}).then(function (response) {
console.log("3");
}).catch(function (error) {
console.log("4");
console.log(error);
});
},
validarUsuario(){
console.log("2");
this.errorPersona=0;
this.errorMostrarMsjPersona =[];
if (!this.email) this.errorMostrarMsjPersona.push("El correo de usuario no puede estar vacío.");
if (!this.usuario) this.errorMostrarMsjPersona.push("El nombre de usuario no puede estar vacío.");
if (!this.password) this.errorMostrarMsjPersona.push("El password no puede estar vacío.");
if (this.errorMostrarMsjPersona.length) this.errorPersona = 1;
return this.errorPersona;
},
}
}
</script>
This is my UserController.php
public function store(Request $request)
{
if (!$request->ajax()) return redirect('/');
DB::beginTransaction();
$usuario = new User();
$usuario-> usuario = $request->usuario;
$usuario-> password = bcrypt($request->password);
$usuario-> condicion = 1;
$usuario->save();
console.log('end');
DB::commit();
}
This is my web.php
Route::get('/main', function () {
return view('contenido/contenido');
})->name('main');
//Route::resource('proyecto', 'ProyectoController', ['except' => 'show']);
Route::get('/user', 'UserController#index');
Route::post('/user/registrar', 'UserController#store');
Route::put('/user/actualizar', 'UserController#update');
Route::put('/user/desactivar', 'UserController#desactivar');
Route::put('/user/activar', 'UserController#activar');
Route::get('/register','Auth\RegisterController#showRegisterForm');

You must need csrf token or disable it.
First for disable
Http/Middleware/VerifyCsrfToken.php
protected $except = [
'/user/registrar'
];
Second for send with csrf your ftemplate
<template>
<div class="login-wrapper border border-light">
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal">
{{ csrf_field() }}
<h2 class="form-signin-heading">Please sign in</h2>
<div class="form-group">
<label for="usuario" class="sr-only">Username</label>
<input v-model="usuario" type="usuario" id="inputEmail" class="form-control" placeholder="Username" required autofocus>
<label for="inputEmail" class="sr-only">Email </label>
<input v-model="email" type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input v-model="password" type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<button class="btn btn-primary" #click="registrarUsuario()">Register</button>
</div>
</form>
</div>
</template>
UPDATE
You can get csrf token from app.blade.php
var csrfToken = $('meta[name="csrf-token"]').attr('content');
Then update your axios.post request
axios.post('/user/registrar',{
'email' : this.email,
'usuario': this.usuario,
'password': this.password
},headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': csrfToken,
}).then(function (response) {
console.log("3");
}).catch(function (error) {
console.log("4");
console.log(error);
});

Related

Why i am getting 'No Access-Control-Allow-Origin'

I am getting this error "Access to XMLHttpRequest at 'http://localhost/api/auth/register' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."
<template>
<div class="container mt-2">
<form autocomplete="off" #submit.prevent="register" method="post">
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.email }">
<label for="email">E-mail</label>
<input type="email" id="email" class="form-control bg-light border-0 small" placeholder="user#example.com" v-model="email">
<span class="help-block" v-if="has_error && errors.email">{{ errors.email }}</span>
</div>
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.password }">
<label for="password">Password</label>
<input type="password" id="password" class="form-control bg-light border-0 small" v-model="password">
<span class="help-block" v-if="has_error && errors.password">{{ errors.password }}</span>
</div>
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.password }">
<label for="password_confirmation">Conform Password</label>
<input type="password" id="password_confirmation" class="form-control bg-light border-0 small" v-model="password_confirmation">
</div>
<div class="alert alert-danger" v-if="has_error && !success">
<p v-if="error == 'registration_validation_error'">Validation error</p>
<p v-else>Please fill all the fields to get registered</p>
</div>
<input type="hidden" name="_token" :value="csrf">
<div class="text-center pb-3">
<button type="submit" class="btn btn-success btn-sm" style="background-color:#00A7F5;border:none;">Register</button>
</div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
email: '',
password: '',
password_confirmation: '',
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
has_error: false,
error: '',
errors: {},
success: false
}
},
methods: {
register() {
var app = this
this.$auth.register({
data: {
email: app.email,
password: app.password,
password_confirmation: app.password_confirmation
},
success: function () {
app.success = true
},
error: function (res) {
app.has_error = true
app.error = res.response.error
app.errors = res.response.errors || {}
}
})
}
}
}
</script>
if fails, response from controller
$a = Validator::make($request->all(), [
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
]);
if ($a->fails())
{
return response()->json([
'status' => 'error',
'errors' => $a->errors()
], 422);
}
if everything ok then
return response()->json(['status' => 'success'], 200);
Please let me know whats wrong with this and is there any better way to handle error. Please share link then, i am not able to handle error correctly.
All helps are appreciated.
CORS policy checks strictly on domain plus port. So make both the same will be the solution.
You need to add CORS Service Provider to your project, like this: https://github.com/barryvdh/laravel-cors

Modal box form submit in Laravel

I have done a Modal form and trying to submit the form, but it is not working.
This is my form
<div class="modal-body">
<div class="card-body">
<form action="{{ url('/admin/modaluser/add')}}" method="POST" id="customerSubmit">
<div class="row">
<div class="col">
#if(session('success'))
<div class="alert alert-success">{{session('success')}}</div>
#endif
#if(session('error'))
<div class="alert alert-error">{{session('error')}}</div>
#endif
#csrf
<div class="row">
<div class="form-group col-md-6">
<label for="name">Name</label>
<input class="form-control" name="name" id="name"
type="text"
placeholder="Enter Name" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="hpcontact">HP Contact No</label>
<input class="form-control" name="hpcontact" id="hpcontact"
type="text"
placeholder="HP Contact No" data-original-title="" title=""
required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="icno">IC No</label>
<input class="form-control" name="icno" id="icno"
type="text"
placeholder="Enter IC No" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="homephone">Home Contact No</label>
<input class="form-control" name="homephone" id="homephone"
type="text"
placeholder="Enter home contact no" data-original-title="" title=""
required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="dob">D.O.B</label>
<input class="form-control" name="dob" id="dob"
type="date"
placeholder="Enter DOB" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="officeno">Office No</label>
<input class="form-control" name="officeno" id="officeno"
type="text"
placeholder="Enter Office No" data-original-title="" title=""
required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="address">Address</label>
<input class="form-control" name="address" id="address"
type="text"
placeholder="Enter Address" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="email">Email</label>
<input class="form-control" name="email" id="email"
type="email"
placeholder="Enter Email" data-original-title="" title=""
required>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
This is my jQuery for the Ajax
$(document).ready(function(){
$('body').on('click','#addcustomer',function(e){
e.preventDefault();
// AJAX request
console.log($('#customerSubmit').serialize())
$.ajax({
method: 'post',
url: '/admin/modaluser/add',
data: $('#customerSubmit').serialize(),
success: function(msg) {
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});
});
});
And this my Controller
public function adduser(Request $request)
{
if(Request::ajax()){
$name = Input::get( 'name' );
$hpcontact = Input::get( 'hpcontact' );
$icno = Input::get( 'icno' );
$homephone = Input::get( 'homephone' );
$dob = Input::get( 'dob' );
$officeno = Input::get( 'officeno' );
$address = Input::get( 'address' );
$email = Input::get( 'email' );
$customer = new Customer();
$customer->name = $name;
$customer->hpcontact = $hpcontact;
$customer->icno = $icno;
$customer->homephone = $homephone;
$customer->dob = $dob;
$customer->officeno = $officeno;
$customer->address = $address;
$customer->email = $email;
$customer->save();
$response = array(
'status' => 'success',
'msg' => 'Customer created successfully',
);
return Response::json($response);
}
else {
echo 'no';
exit;
}
}
And finally, this is my Router
Route::post('modaluser/add', 'CustomerController#adduser')->name('customer.adduser');
When I click the button, nothing has happened. But this error is coming.
POST http://127.0.0.1:8000/admin/modaluser/add 500 (Internal Server Error)
And showing me the console error, which is defined in the ajax. Is there anything wrong I am doing. This is my First Ajax in Laravel. Please help me to solve this. Thanks in advance.
add /admin into your route:
Route::post('admin/modaluser/add', 'CustomerController#adduser')->name('customer.adduser');
and change url path in ajax:
$(document).ready(function(){
$(document).on('submit','#customerSubmit',function(e){
e.preventDefault();
// AJAX request
console.log($(this).serialize())
$.ajax({
method: 'post',
url: "{{route('customer.adduser')}}",
data: $(this).serialize(),
success: function(msg) {
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});
});
});
remove form action:
<form action="" method="POST" id="customerSubmit">
You should check all class used paths declared on top of the controller or not. You should add the CSRF header in your ajax request.
$.ajax({
method: 'post',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "route name or url",
data: $(this).serialize(),
success: function(msg) {
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});

Data Not Submitting to Database

I'm making a contact page but the form data is not saving to the database. What's the solution?
ContactController.php
public function contact()
{
if($request->isMethod('post'))
{
$data = $request->all();
}
$contact = new Contact;
$contact->name = $data['contact_name'];
$contact->email = $data['contact_email'];
$contact->subject = $data['contact_subject'];
$contact->body = $data['description'];
$category->save();
return redirect()->back()->with('flash_message_success',
'Your message has been sent successfully');
}
contact.blade.php
<form action="{{ url('/contact') }}" id="main-contact-form" class="contact-form row" name="contact-form" method="post">
{{ csrf_field() }}
<div class="form-group col-md-6">
<input type="text" name="contact_name" class="form-control" required="required" placeholder="Name">
</div>
<div class="form-group col-md-6">
<input type="email" name="contact_email" class="form-control" required="required" placeholder="Email">
</div>
<div class="form-group col-md-12">
<input type="text" name="contact_subject" class="form-control" required="required" placeholder="Subject">
</div>
<div class="form-group col-md-12">
<textarea name="description" id="message" required="required" class="form-control" rows="8" placeholder="Your Message Here"></textarea>
</div>
<div class="form-group col-md-12">
<input type="submit" name="submit" class="btn btn-primary pull-right" value="Submit">
</div>
</form>
Routes:
Route::get('contact', function(){
return view('contact');
});
Route::post('contact', function(){
return view('contact');
});
Use $contact->save(); not $category->save(); and also remove the if statement (for now): if($request->isMethod('post')) {
Your route should be:
Route::post('contact', 'ContactController#contact')->name('contact');

getting typerror in Vue JS while trying to bind the JSON data in select model

I want to bind the select option with returned JSON data. However, when I do the API call and set the options model groups to the returned JSON, I get the error 'TypeError: Cannot set property 'groups' of undefined'.
Here is the vue file
<template>
<div class="register">
<div class="container">
<div class="row">
<div class="col">
<h3 class="mb-10">Register as a volunteer</h3>
<form action="">
<div class="form-group">
<label for="first_name">First Name</label>
<input type="text" v-model="first_name" placeholder="First Name" class="form-control" id="first_name">
</div>
<div class="form-group">
<label for="last_name">Last Name</label>
<input type="text" v-model="last_name" placeholder="Last Name" class="form-control" id="last_name">
</div>
<div class="form-group">
<label for="group">Select Institution/Organization/Company</label>
<select v-model="group" class="form-control" id="group">
<option v-for="group in groups" v-bind:name="name">{{ group.code }}</option>
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="text" v-model="adv_phone" placeholder="Phone" class="form-control" id="phone">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" v-model="adv_password" class="form-control" id="password" placeholder="Password">
</div>
<div class="form-group">
<label for="confirm-password">Confirm Password</label>
<input type="password" v-model="adv_password" class="form-control" id="confirm-password" placeholder="Confirm Password">
</div>
<div class="from-group">
<input type="submit" class="btn btn-primary" value="Register">
<router-link :to="{name:'home'}">
<a class="btn btn-outline-secondary">Cancel</a>
</router-link>
</div>
</form>
</div>
</div>
</div>
<div class="register-form"></div>
</div>
</template>
<script>
export default {
mounted(){
this.getGroups()
},
data (){
return {
group: '',
groups:'',
first_name:'',
last_name:'',
adv_email:'',
adv_phone:'',
adv_password:'',
confirm_password:''
}
},
methods:{
getGroups(){
axios.get('/api/group/get/all')
.then(function (response) {
console.log(response);
this.groups = response.data;
//console.log(groups);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
}
}
}
</script>
and here is my json returned
[{"id":8,"name":"Villa Maria Academy","code":"Vil-9458-3786","advisors":25,"students":99,"subscription_time":99,"subscription_type":0,"admin_name":"","admin_email":"","phone":"817879234","address":"Abcde street","state":"Pennsylvania","zip":16502,"apt":"","city":"Erie"},{"id":9,"name":"Cathedral Prep","code":"Cat-1959-1432","advisors":99,"students":99,"subscription_time":99,"subscription_type":0,"admin_name":"","admin_email":"","phone":"0","address":"","state":"","zip":0,"apt":"","city":""}]
Why am I getting a type error, when I set this.groups = response.data?
You can use arrow function to fix problem.
methods:{
getGroups(){
axios.get('/api/group/get/all')
.then(response => {
console.log(response);
this.groups = response.data;
//console.log(groups);
})
.catch(error => {
console.log(error);
})
.then(() => {
// always executed
});
}
}

How to get Output it showing no any error & output?

The contoller shows output error1 it does not shoe even row(),and does not give any error in developer tool. it get the file from ajax users_controller but does not work & issue is contant.
This is the form:
<form class="form-signin" >
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="name" class="sr-only">Username</label>
<input type="text" id="name" class="form-control" placeholder="Username" autofocus><br/>
<label for="Password" class="sr-only">Password</label>
<input type="text" id="password" class="form-control" placeholder="Password">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<span class="error"></span>
</form>
These are the scripts:
<script>
$(document).ready(function(){
$('form').on('submit',function(){
var username = $('#name').val();
var password = $('#password').val();
$.ajax({
type:'post',
url:'users_controller/login_check',
data: {
username:'username',
password:'password'
},
success:function(result)
{
if(result !== 'error')
{
window.location.href=result;
}
else
{
$('.error').html('');
$('.error').html('<p class="alert alert-danger">Invalid username or password</p>');
$('.error').show();
}
}
});
return false;
});
});
This is controller file:
public function login_check()
{
$username = $this->input->post('username',TRUE);
$password = $this->input->post('password',TRUE);
$this->load->model('users_model');
//$row = $this->load->users_model('getUsers');
$row = $this->users_model->getUsers($username,$password);
if($row)
{
if($this->username === $username && $this->password === $password)
{
$this->session->set_userdata('user_id',$row->user_id);
$this->session->set_userdata('user_name',$row->username);
echo base_url('users_controller');
}
else
{
echo "error";
}
}
else{
echo "error1";
print_r($row);
}
}
The contoller shows output error1 it does not shoe even row(),and does not give any error in developer tool.

Resources