Why am getting method not allowed error when saving the data in Laravel? - laravel

In my application, I am getting the error method not allowed when trying to save the data. I am posting my codes here, please someone look into this and help me.
HolidayAdd.vue
<template>
<layout>
<form #submit.prevent="handleSubmit">
<div class="input-group">
<div class="input-group-prepend">
<span for="name" class="input-group-text">First Name and Last Name </span>
</div>
<input type="text" class="form-control" name="firstname" placeholder="Enter your First Name" v-model="holiday.fname" id="fname">
<input type="text" class="form-control" name="lastname" placeholder="Enter your Last Name" v-model="holiday.lname" id="lname">
</div>
<br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Start Date </span>
</div>
<input type="date" class="form-control" name="startdate" v-model="holiday.sdate" id="sdate">
</div>
<br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">End Date</span>
</div>
<input type="date" class="form-control" name="enddate" v-model="holiday.edate" id="edate">
</div>
<br>
<button type="submit" class="btn btn-info">Apply</button>
</form>
</layout>
</template>
<script>
import Layout from './../../Shared/Layout'
export default {
components: {
Layout
},
data() {
return {
holiday: {
fname: '',
lname: '',
sdate: '',
edate: ''
}
}
},
methods: {
async handleSubmit() {
let response = await this.$inertia.post('/holiday/store', this.holiday)
}
}
}
</script>
HolidayController.php
public function store(Request $request)
{
$holiday = $request->validate([
'firstname' => 'required',
'lastname' => 'required',
'startdate' => 'required',
'enddate' => 'required'
]);
Holiday::create($holiday);
return redirect()->route('holiday.index')->with('success', 'Record Inserted Successfully');
}
web.php
Route::resource('holiday', 'HolidayController');
As far as I know, there is no error, then why I am getting a 405 error here?

In your Vue code your should use POST request to the '/holiday' instead of the '/holiday/store'.
Defining resource route is equivalent to:
Route::get('/holiday', 'HolidayController#index');
Route::get('/holiday/create', 'HolidayController#create');
Route::post('/holiday', 'HolidayController#store');
Route::get('/holiday/{holiday}', 'HolidayController#show');
Route::get('/holiday/{holiday}/edit', 'HolidayController#edit');
Route::put('/holiday/{holiday}', 'HolidayController#update');
Route::patch('/holiday/{holiday}', 'HolidayController#update');
Route::delete('/holiday/{holiday}', 'HolidayController#destroy');
https://laravel.com/docs/5.8/controllers#resource-controllers

Your url '/holiday/store' dose not much Route::resource('holiday', 'HolidayController');
Fix
await this.$inertia.post('holiday', this.holiday)
To check routes and its corresponding URIs
Run the following command
php artisan route:list

Related

Validation on clonned fields in vue js and laravel

I am stuck with some issue while using vue and laravel. From the vue JS I am clonning the fields like address or cities to multiple clone. I am trying to submit the form without filling those fields It should show the errors under each box (validation error).
here is the code I am using ---
in the .vue file ---
<template>
<div class="container">
<h2 class="text-center">Add User</h2>
<div class="row">
<div class="col-md-12">
<router-link :to="{ name: 'Users' }" class="btn btn-primary btn-sm float-right mb-3">Back</router-link>
</div>
</div>
<div class="row">
<div class="col-md-12">
<ul>
<li v-for="(error, key) in errors" :key="key">
{{ error }}
</li>
</ul>
<form>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" v-model="user.name">
<span class="text-danger">{{ errors.name }}</span>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" v-model="user.email">
<span class="text-danger">{{ errors.email }}</span>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" v-model="user.password">
<span class="text-danger">{{ errors.password }}</span>
</div>
<button type="button" class="btn btn-primary btn-sm float-right mb-3" #click="addMoreAddress()">Add More</button>
<template v-for="(addressNo, index) in addresses">
<h5>Address ({{addressNo}}) </h5>
<div class="form-group">
<label>Address</label>
<textarea type="text" rows="5" class="form-control" v-model="user.addresses[index].address"></textarea>
<span class="text-danger">{{ errors.addresses }}</span>
</div>
<div class="form-group">
<label>City</label>
<input type="text" class="form-control" v-model="user.addresses[index].cities">
<span class="text-danger">{{ errors.addresses }}</span>
</div>
</template>
<button type="button" class="btn btn-primary" #click="createUser()">Create</button>
</form>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
user: {
name: '',
email: '',
password: '',
addresses: [
{
address: '',
cities : ''
}
]
},
errors: {},
addresses: 1
}
},
methods: {
createUser() {
let vm = this;
axios.post('api/users', vm.user)
.then(({data}) => {
// vm.$router.push('/users');
})
.catch((error) => {
let errorsMessages = error.response.data;
console.log(errorsMessages);
const errors = {};
if (Object.keys(errorsMessages).length) {
Object.keys(errorsMessages.errors).forEach((key) => {
errors[key] = errorsMessages.errors[key][0];
});
}
vm.errors = errors;
});
},
addMoreAddress() {
this.user.addresses.push({address:'',cities:''});
this.addresses++;
}
}
}
</script>
and in the laravel I am using the following code (for validation)---
$data = Validator::make($request->all(), [
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|min:8',
'addresses.*.address' => 'required',
'addresses.*.cities' => 'required',
]);
$errors = $data->errors();
if ($data->fails()) {
return response()->json([
'errors' => $errors
], 422);
}
When I try to submit the form without filling the record. from the api it returing like ---
But I am not able to show the error under each field for address and city. If i print the response it works fine and for name as well. I want the same error message view like showing under name field.
Thanks in advance for helping hands..

Why am getting unexpected redirect (302) error when saving the data in Laravel?

In my application, I am getting the error 302 when trying to save the data. I am posting my codes here, please someone look into this and help me.
HolidayAdd.vue
<template>
<layout>
<div class="container">
<form #submit.prevent="handleSubmit">
<div class="form-group">
<label for="fname">First Name</label>
<input id="fname" type="text" class="form-control" name="ftname" placeholder="Enter your First Name" v-model="holiday.fname">
</div>
<div class="form-group">
<label for="lname">Last Name</label>
<input id="lname" type="text" class="form-control" name="lastname" placeholder="Enter your Last Name" v-model="holiday.lname">
</div>
<div class="form-group">
<label for="sdate">Start Date</label>
<input type="date" class="form-control" name="sdate" v-model="holiday.sdate" id="sdate">
</div>
<div class="form-group">
<label for="edate">End Date</label>
<input type="date" class="form-control" name="edate" v-model="holiday.edate" id="edate">
</div>
<button class="btn btn-info">Apply</button>
</form>
</div>
</layout>
</template>
<script>
import Layout from './../../Shared/Layout'
export default {
components: {
Layout
},
data() {
return {
holiday: {
fname: '',
lname: '',
sdate: '',
edate: ''
}
}
},
methods: {
async handleSubmit() {
let response = await this.$inertia.post('/holiday', this.holiday)
}
}
}
</script>
HolidayController.php
public function store(Request $request)
{
$holiday = $request->validate([
'firstname' => 'required',
'lastname' => 'required',
'startdate' => 'required',
'enddate' => 'required'
]);
Holiday::create($holiday);
return redirect()->route('holiday.index');
}
web.php
Route::group(['middleware' => 'auth'], function() {
Route::resource('holiday', 'HolidayController');
});
As far as I know, there is no error, then why I am getting a 302 error here?
This is happening because of the validation at your store action. you need to change
holiday: {
fname: '',
lname: '',
sdate: '',
edate: ''
}
to
holiday: {
'firstname' : '',
'lastname' : '',
'startdate' : '',
'enddate' : ''
}
and then change v-model to the new names. then you need to do some validation in your front-end.also you shouldn't return a redirect response if request is ajax.

Laravel, adding data to database after verifying ReCaptcha

I'm using ReCaptcha in my Laravel project, done it with this
tutorial.
I need to create a page where user can post his message after checking captcha.
I have created a modal dialog where user can fill in data like this :
<form class="form-horizontal" action="" method="post">
<div class="form-group error">
<label for="messageName" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control has-error" id="name" name="name" placeholder="Your name" value=""
ng-model="message.name" ng-required="true">
<span class="help-inline"
ng-show="GBM.text.$invalid && GBM.text.$touched">Required</span>
</div>
</div>
<div class="form-group error">
<label for="messageEmail" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control has-error" id="email" name="email" placeholder="E-mail" value=""
ng-model="message.email" ng-required="true">
<span class="help-inline"
ng-show="GBM.email.$invalid && GBM.email.$touched">Required</span>
</div>
</div>
<div class="form-group error">
<label for="messageLink" class="col-sm-3 control-label">Web</label>
<div class="col-sm-9">
<input class="form-control" rows="3" class="form-control has-error" id="web" name="web" placeholder="Link for your web" value="" ng-model="message.web" ng-required="false" >
</div>
</div>
<div class="form-group error">
<label for="messageText" class="col-sm-3 control-label">Comment</label>
<div class="col-sm-9">
<textarea class="form-control" rows="3" class="form-control has-error" id="comment" name="comment" placeholder="Your comment" value="" ng-model="message.text" ng-required="true" ></textarea>
<span class="help-inline"
ng-show="GBM.text.$invalid && GBM.text.$touched">Required</span>
</div>
</div>
{!! csrf_field() !!}
<!-- recaptcha -->
{{Request::is('contactd')}}
<div class="form-group">
<div class="col-md-9">
<div class="g-recaptcha" data-sitekey="{{env('GOOGLE_RECAPTCHA_KEY')}}"></div>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-9 control-label"></label>
<div class="col-md-9">
<button type="submit" name="send" class="btn btn-primary btn-lg btn-block">Add new message <span class="fa fa-paper-plane-o"></span></button>
</div>
</div>
</form>
For a route I got it like this:Route::post('contact','ContactController#store');
And here is the problem, in my controller i got this code to verify captcha:
public function store(ReCaptchataTestFormRequest $request){
return "Captcha done right! ";}
And this code to save data to database
public function store(Request $request)
{
$this->validate($request, [ 'name' => 'required|max:255' ]);
$this->validate($request, [ 'email' => 'required | email' ]);
$this->validate($request, [ 'comment' => 'required' ]);
$ip = $_SERVER['REMOTE_ADDR'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$guestbook = Guest_books::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'web' => $request->input('web'),
'comment' => $request->input('comment'),
'ip' => $ip,
'browser' => $browser
]);
return $guestbook;
}
So the question is: What to write in Controller for project to verify Captcha and then post it to database?
The tutorial you've followed teaches you how to create a custom validation rule which you can then use when validating requests, either through a Form Request or directly in your controller.
The mistake you've made in your controller is that you've called validate multiple times, instead you should pass it an array containing all of your rules, including your recaptcha rule, e.g:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email',
'comment' => 'required',
'g-recaptcha-response' => 'required|recaptcha',
]);
// ...
}
Additionally, you should note that the store method should always return a redirect.

How to upload picture and store to database in Laravel 5

I need to upload picture and store to database in Laravel 5.
My current code is:
Form:
<form method="POST" enctype="multipart/form-data" action="{{ url('products/new) }}">
{!! csrf_field() !!}
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" required>
</div>
<div class="form-group">
<label for="image">Image</label>
<input type="file" id="image">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
Controller:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:100|unique:products',
]);
$input = $request->all();
Product::create($input);
return redirect('products');
}
The function $request->hasFile('image')) returns false.
hasFile('image') returns false because there is not an input with name 'image', only the id is 'image'
You should give it a name property, since that's the way the inputs are sent through http.
Instead of this:
<input type="file" id="image">
use this
<input name="image" type="file" id="image">
and in your validator use this:
$this->validate($request, [
'image' => 'required|max:100|unique:products',
]);

stripe token is not passing

I have an application built in Laravel 4 and uses this package
I am following this tutorial
This is the error I am getting http://postimg.org/image/c4qwjysgp/
My issue is $token is not correctly passing or the $token is empty.
I have already done a var_dump($token); die(); and get nothing but a white screen so not data is passing.
Here is the view
#extends('layouts.main')
#section('content')
<h1>Your Order</h1>
<h2>{{ $download->name }}</h2>
<p>£{{ ($download->price/100) }}</p>
<form action="" method="POST" id="payment-form" role="form">
<input type="hidden" name="did" value="{{ $download->id }}" />
<div class="payment-errors alert alert-danger" style="display:none;"></div>
<div class="form-group">
<label>
<span>Card Number</span>
<input type="text" size="20" data-stripe="number" class="form-control input-lg" />
</label>
</div>
<div class="form-group">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc" class="form-control input-lg" />
</label>
</div>
<div class="form-group">
<label>
<span>Expires</span>
</label>
<div class="row">
<div class="col-lg-1 col-md-1 col-sm-2 col-xs-3">
<input type="text" size="2" data-stripe="exp-month" class="input-lg" placeholder="MM" />
</div>
<div class="col-lg-1 col-md-1 col-sm-2 col-xs-3">
<input type="text" size="4" data-stripe="exp-year" class="input-lg" placeholder="YYYY" />
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Submit Payment</button>
</div>
</form>
#stop
Here is the route
Route::post('/buy/{id}', function($id)
{
Stripe::setApiKey(Config::get('laravel-stripe::stripe.api_key'));
$download = Download::find($id);
//stripeToken is form name, injected into form by js
$token = Input::get('stripeToken');
//var_dump($token);
// Charge the card
try {
$charge = Stripe_Charge::create(array(
"amount" => $download->price,
"currency" => "gbp",
"card" => $token,
"description" => 'Order: ' . $download->name)
);
// If we get this far, we've charged the user successfully
Session::put('purchased_download_id', $download->id);
return Redirect::to('confirmed');
} catch(Stripe_CardError $e) {
// Payment failed
return Redirect::to('buy/'.$id)->with('message', 'Your payment has failed.');
}
});
Here is the js
$(function () {
console.log('setting up pay form');
$('#payment-form').submit(function(e) {
var $form = $(this);
$form.find('.payment-errors').hide();
$form.find('button').prop('disabled', true);
Stripe.createToken($form, stripeResponseHandler);
return false;
});
});
function stripeResponseHandler(status, response) {
var $form = $('#payment-form');
if (response.error) {
$form.find('.payment-errors').text(response.error.message).show();
$form.find('button').prop('disabled', false);
} else {
var token = response.id;
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
$form.get(0).submit();
}
}
Here is the stripe.php in package
<?php
return array(
'api_key' => 'sk_test_Izn8gXUKMzGxfMAbdylSTUGO',
'publishable_key' => 'pk_test_t84KN2uCFxZGCXXZAjAvplKG'
);
Seems like the Config::get might be wrong.
It would have to be written this way.
Stripe::setApiKey(Config::get('stripe.api_key'));
I figured out the problem. In the source for the external javascript file, the "/" was missing at the beginning of the relative path. That is why the javascript file for the homepage was rendering fine but the /buy page was not rendering the javascript file.

Resources