Vus.js Laravel Update records not working - laravel

i am beginner of vue.js and laravel programming successfully done add records and view records from the database.but i can't update the records.when check the error through the console. it displayed the following
Failed to load resource: the server responded with a status of 404 (Not Found)
i don't know how to solve them.my api is working successfully.
what i done so far i attached below.
Laravel
Routes
Route::put('/update/{id}',[App\Http\Controllers\ContactController::class, 'update']);
ContactController
public function update(Request $request, $id)
{
$contact = new Contact([
'name' => $request->name,
'address' => $request->address,
'nic' => $request->nic
]);
$contact->update();
return response()->json('Contact Updateddd!');
}
Model
class Contact extends Model{
protected $table = "contact";
protected $primaryKey = "id";
protected $fillable = ["name", "address", "nic"];
}
Front End Vue JS
Save records and Updating records i adding the same form with validation. save is working but update dosen't working.
<form #submit.prevent="save">
<div class="form-group">
<label>Employee Name</label>
<input v-model="task.name" type="text" class="form-control">
</div>
<div class="form-group">
<label>Employee Address</label>
<input v-model="task.address" type="text" class="form-control" >
</div>
<div class="form-group">
<label>Nic</label>
<input v-model="task.nic" type="text" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
table records view from the database successfullly i attached code below. each rows i put the edit button for edit. when i click the edit button editable row records are passing to the form successfully. after that make the changes and click edit records not i updated what is the error i got i attached above.
table code
<td>{{ task.id }}</td>
<td>{{ task.name }}</td>
<td>{{ task.address }}</td>
<td>{{ task.nic }}</td>
<td>
<button type="button" class="btn btn-primary" #click="edit(task)">Edit</button>
<button type="button" class="btn btn-danger" #click="remove(task)">Delete</button>
</td>
Save and update code . save is working update only not working please check the update code
i attached the full code for easy to find out the error.
import Vue from 'vue';
import axios from 'axios';
Vue.use(axios)
export default {
name: 'Crud',
data () {
return {
result: {},
task:{
id: '',
name: '',
address: '',
nic: ''
}
}
},
created() {
console.log("created() called.....");
this.loadTaks();
},
mounted() {
console.log("mounted() called.......");
},
methods: {
loadTaks()
{
Vue.use(axios);
console.log("LoadTasks() calling....");
// var page = "http://localhost:8088/api/v1/employee/get-all-employees";
var page = "http://127.0.0.1:8000/api/contact";
axios.get(page)
.then(
({data})=>{
console.log(data);
this.result = data;
}
);
},
save()
{
if(this.task.id == '')
{
this.saveData();
}
else
{
this.updateData();
}
},
saveData()
{
axios.post('http://127.0.0.1:8000/api/save', this.task)
.then(
({data})=>{
this.loadTaks();
this.task.name = '';
this.address = '',
this.nic = '',
alert("saved!!!");
}
)
},
updateData()
{
var url = '127.0.0.1:8000/api/update/'+this.task.id;
axios.put(url, this.task)
.then(
({data})=>{
this.task.name = '';
this.address = '',
this.nic = ''
this.id = ''
alert("Updated!!!");
this.loadTaks();
}
);
},
edit(task){
this.task = task;
},
remove(task){
var url = 'http://127.0.0.1:8000/api/contact/delete/'+this.task.id;
axios.delete();
}
}
}
</script>
Have a problem on the controller update funtion what was the error here
public function update(Request $request, $id)
{
$contact = new Contact([
'name' => $request->name,
'address' => $request->address,
'nic' => $request->nic
]);
$contact->update();
return response()->json('Contact Updateddd!');
}

Related

422 Unprocessable Entity Error. I tried upload Excel file to import data but it is not working

This is my code, i use vuejs and laravel. The function I am doing is both saving the Course and also importing the Excel file to get the data in the file. But when saving the Course is normal, but when it comes to running the validate excel file line, the error is not received. Even though I gave it a name and console.log came out. Can you help me fix it? Thank you so much.
Component - template tag
<form #submit.prevent="store()" #keydown="form.onKeydown($event)">
<div class="form-group">
<label class="form-label">Courses</label>
<select class="form-control" name="education_program_course" v-model="form.education_program_course">
<option value="" disabled selected="">Select option</option>
<option value="" disabled>-------</option>
<option v-for="course in courses" :key="course.course_code" :value="course.course_code">{{ course.course_name }}</option>
</select>
</div>
<div class="form-group">
<label class="form-label">Excel File</label>
<input type="file" class="form-control" id="file_data" name="file_data" ref="fileupload" #change="onFileChange">
</div>
<div class="card-footer text-right">
<button :disabled="form.busy" class="btn btn-success btn-lg mt-1" type="submit">Save</button>
</div>
</form>
Component - script tag
export default: {
data() {
return {
file_data: "",
form: new Form({
education_program_course
}),
},
methods: {
onFileChange(e) {
this.file_data = e.target.files[0];
},
store() {
this.form.busy = true;
let formData = new FormData();
formData.append('file_data', this.file_data);
this.form.post('../../api/admin/program/education', formData, {
headers: { 'content-type': 'multipart/form-data' }
})
.then(res => {
if(this.form.successful){
this.$snotify.success('Sucessful!');
this.form.clear();
this.form.reset();
}
})
.catch(err => {
this.$snotify.error(err.response.data.errors.file_data[0]);
});
},
}
}
}
Controller
$data = $request->validate([
'education_program_course' => ['required'],
'file_data' => ['required', 'file', 'mimes:xls,xlsx']
]);
$program = new EducationProgram();
$program->education_program_course = $data['education_program_course'];
$path = $request->file($data['file_data'])->getRealPath();
Excel::import(new ProgramDetailImport, $path);
You should append 'education_program_course' on your formdata.
formData.append('education_program_course', this.form.education_program_course);
I have solved this problem. Change change at script tag -> store()
from:
let formData = new FormData();
formData.append('file_data', this.file_data);
to:
if(document.getElementById("file_data").files[0]){
this.form.file_data = document.getElementById("file_data").files[0];
}
Adding file_date in form: new Form and remove formData in this.form.post.

The GET method is not supported for this route. Supported methods: POST. when i want to input data

I tried to solve this Laravel - Vue input problem and I can't find the solution. I follow my teacher's tutorial and it's work. But when I tried mine and open the console, I found it show error with message :
`Access to XMLHttpRequest at 'http://localhost/lat_laravel-vue1/public/api/siswa/tambahsiswa' from origin 'http://localhost:8080' 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.`
and when I click the Laravel's link, it show me an error message
"The GET method is not supported for this route. Supported methods: POST.".
I use Laravel 5.8 version.
https://i.stack.imgur.com/0z6C2.png
Laravel Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\siswaModel;
use Illuminate\Support\Facades\Validator;
header('Access-Control-Allow-Origin: *');
class siswaController extends Controller
{
public function simpan(Request $req)
{
$validator = Validator::make($req->all(), [
'nama_siswa' => 'required',
'tanggal_lahir' => 'required',
'gender' => 'required',
'id_kelas' => 'required'
]);
if ($validator->fails()) {
return Response()->json($validator->errors());
}
$simpan = siswaModel::create([
'nama_siswa' => $req->nama_siswa,
'tanggal_lahir' => $req->tanggal_lahir,
'gender' => $req->gender,
'id_kelas' => $req->id_kelas,
'alamat' => $req->alamat
]);
if ($simpan) {
$data['status'] = true;
$data['message'] = "Sukses Menambahkan Siswa";
} else {
$data['status'] = false;
$data['message'] = "Gagal Menambahkan Siswa";
}
return $data;
}
}
Routes
Route::post('/tambahsiswa', 'siswaController#simpan');
Vue file
<div class="container">
Nama Siswa
<input type="text" name="nama_siswa" v-model="nama_siswa" class="form-control">
<br>
Tanggal Lahir
<input type="date" name="tanggal_lahir" v-model="tanggal_lahir" class="form-control">
<br>
Gender
<select name="gender" v-model="gender" class="form-control">
<option></option>
<option v-for="gender in listgender" :key="gender.key" value="{{gender.key}}">{{gender.val}}</option>
</select>
<br>
Alamat
<textarea rows="4" class="form-control" v-model="alamat" name="alamat"></textarea>
<br>
Kelas
<select name="kelas" v-model="kelas" class="form-control">
<option></option>
<option v-for="kelas in listkelas" :key="kelas.id" value="{{kelas.id}}">{{kelas.nama_kelas}}</option>
</select>
<br>
<button class="btn btn-primary" #click="simpansiswa()">Simpan</button>
</div>
</template>
<script>
export default {
name: "Tambahsiswa",
data() {
return {
'listgender': [
{ key: 'L', val: 'Laki-laki' },
{ key: 'P', val: 'Perempuan' }
],
listkelas: [],
nama_siswa: '',
tanggal_lahir: '',
gender: '',
alamat: '',
kelas: '',
}
},
methods: {
getkelas:function() {
this.axios.get('http://localhost/lat_laravel-vue1/public/api/getkelas').then((result) => {
this.listkelas = result.data
})
},
simpansiswa:function() {
var datasiswa = {
nama_siswa: this.nama_siswa,
tanggal_lahir: this.tanggal_lahir,
gender: this.gender,
alamat: this.alamat,
id_kelas: this.kelas
}
this.axios.post('http://localhost/lat_laravel-vue1/public/api/siswa/tambahsiswa', datasiswa).then((result) => {
console.log(result)
})
}
},
mounted(){
this.getkelas();
}
}
</script>```
Are your Laravel and Vue is in one project ?
No : Laravel 5.8 default has no CORS. Can you check installed any package to config CORS ?
Yes : Try using Axios with CDN instead of javascript package and post data again.
https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

How to import data from excel file to mysql using vue Js and Laravel

I am having a problem trying to export an excel file to database using axios. Am able to console the file
but cant figure out to post the data.
I get this error
Failed to load resource: the server responded with a status of 422 (Unprocessable Entity) app.js:716
My view
<form enctype="multipart/form-data">
#csrf
<div class="form-group">
<table class="table">
<tr>
<td width="40%" align="right"><label>Select File for Upload</label></td>
<td width="30">
<input type="file" #change="getExcelData" name="select_file" />
</td>
<td width="30%" align="left">
<input type="submit" name="upload" class="btn btn-primary" value="Upload">
</td>
</tr>
</table>
</div>
</form>
The vue function
getExcelData(e){
//const formData = new FormData();
const file = e.target.files[0];
console.log(file);
//formData.append('file', file);
axios.post("/import_excel/import").then(function(response){
// this.users=response.data;
console.log("working now");
console.log(file);
console.log(response)
}.bind(this))
},
My controller file
function import(Request $request)
{
$this->validate($request, [
'select_file' => 'required|mimes:xls,xlsx'
]);
$path = $request->file('select_file')->getRealPath();
$data = Excel::load($path)->get();
if($data->count() > 0)
{
foreach($data->toArray() as $key => $value)
{
foreach($value as $row)
{
$insert_data[] = array(
'userName' => $row['userName'],
'userPassword' => $row['userPassword'],
'timePackage' => $row['timePackage'],
'location' => $row['location'],
'Assigned' => $row['Assigned']
);
}
}
if(!empty($insert_data))
{
DB::table('hotspot_users')->insert($insert_data);
}
}
return back()->with('success', 'Excel Data Imported successfully.');
}
Route
Route::post('/import_excel/import', 'ImportExcelController#import');

How to add Recaptcha v2 to Laravel and Vue js?

I'm following this article on how to add Recaptcha v2 to a Laravel and Vue js project.
https://www.itechempires.com/2018/05/how-to-implement-google-recapcha-with-vuejs-and-laravel-5-6/
I'm trying to implement it in my project but I'm getting this error on the page:
The recaptcha verification failed. Try again.
And in the network tab this error:
{recaptcha: ["The recaptcha verification failed. Try again."]}
And in the console:
POST http://highrjobsadminlte.test/submit 422 (Unprocessable Entity)
I'm trying to implement this on a Contact Form on my Contact.vue page.
Contact.vue:
<form #submit.prevent="submit">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name" v-model="fields.name" />
<div v-if="errors && errors.name" class="text-danger" style="font-size: 13px;">{{ errors.name[0] }}</div>
</div>
<div class="form-group">
<label for="email">E-mail</label>
<input type="email" class="form-control" name="email" id="email" v-model="fields.email" />
<div v-if="errors && errors.email" class="text-danger" style="font-size: 13px;">{{ errors.email[0] }}</div>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" id="message" name="message" rows="5" v-model="fields.message"></textarea>
<div v-if="errors && errors.message" class="text-danger" style="font-size: 13px;">{{ errors.message[0] }}</div>
</div>
<div class="form-group">
<vue-recaptcha
v-model="fields.recaptcha"
ref="recaptcha"
#verify="onVerify"
sitekey="6LcAHcoZAAAAAFDOejn9e2LrogSpF41RMlXtrpDa">
</vue-recaptcha>
</div>
<div v-if="errors && errors.recaptcha" class="text-danger" style="font-size: 13px;">{{ errors.recaptcha[0] }}</div>
<button type="submit" class="btn btn-primary mt-3">Send message</button>
</form>
export default {
name: "Contact",
data() {
return {
fields: {},
errors: {},
}
},
methods: {
onVerify(response) {
this.fields.recaptcha = response;
},
submit() {
this.errors = {};
axios.post('/submit', this.fields, {
headers:{
'Content-Type':'application/json',
'Accept':'application/json'
}
}).then(({data: {fields}}) => {
this.$toast.success('Message sent successfully!');
this.$refs.recaptcha.reset();
}).catch(error => {
if (error) {
this.errors = error.response.data.errors || {};
}
});
},
},
}
Recaptcha.php (This is a rule):
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Zttp\Zttp;
class Recaptcha implements Rule
{
const URL = 'https://www.google.com/recaptcha/api/siteverify';
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
return Zttp::asFormParams()->post(static::URL, [
'secret' => config('services.recaptcha.secret'),
'response' => $value,
'remoteip' => request()->ip()
])->json()['success'];
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'The recaptcha verification failed. Try again.';
}
/**
* Determine if Recaptcha's keys are set to test mode.
*
* #return bool
*/
public static function isInTestMode()
{
return Zttp::asFormParams()->post(static::URL, [
'secret' => config('services.recaptcha.secret'),
'response' => 'test',
'remoteip' => request()->ip()
])->json()['success'];
}
}
ContactFormController.php:
<?php
namespace App\Http\Controllers;
use App\Mail\ContactEmail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Rules\Recaptcha;
class ContactFormController extends Controller
{
public function submit(Request $request, Recaptcha $recaptcha) {
$this->validate($request, [
'name' => 'required|string',
'email' => 'required|email',
'message' => 'required',
'recaptcha' => ['required', $recaptcha],
]);
$contact = [];
$contact['name'] = $request->get('name');
$contact['email'] = $request->get('email');
$contact['subject'] = $request->get('subject');
$contact['message'] = $request->get('message');
// Mail Delivery logic goes here
Mail::to(config('mail.from.address'))->send(new ContactEmail($contact));
return response(['contact' => $contact], 200);
}
}
web.php:
Route::post('/submit', 'ContactFormController#submit');
And I have set recaptcha key and secret in config/services.php to point to my .env variables which are set in my .env file.

Error when pass FormData from vue to laravel controller

i'm working on an laravel vuejs spa.
I try to update a post from the admin. I send the form datas on creating a new FromData who are sending with and axios request.
But the controller send me the error:
message: "The given data was invalid."
errors: {name: ["The name field is required."], description: ["The description field is required."]}
Here is the post/edit.vue
<template>
<div class="post-edit">
<form id="form" #submit.prevent="createPost">
<!-- Title -->
<div class="form-group">
<label for="title" class="form-label">Title</label>
<input id="title" v-model="post.title" :title="post.title" type="text"
name="title" class="form-control"
>
</div>
<!-- Category -->
<div class="form-group">
<label for="category" class="form-label">Category</label>
<select id="category" v-model="post.category" :value="post.category" :category="post.category"
name="category" class="form-control"
>
<option disabled :value="post.category">
Choisir une catégorie
</option>
<option v-for="(category) in categories" :key="category.id" :value="post.category">
{{ category.name }}
</option>
</select>
</div>
<div class="post-edit-image">
<img :src="path + post.image" alt="">
</div>
<!-- Image -->
<div class="form-group post-edit-select-image">
<label for="content" class="form-label">Image</label>
<input type="file" name="image" class="form-control" #change="selectedImage">
</div>
<!-- Content -->
<div class="form-group">
<label for="content" class="form-label">Content</label>
<editor
id="content"
v-model="post.content"
api-key="the-api-key"
:init="{
height: 500,
menubar: false,
plugins: [
'advlist autolink lists link image charmap print preview anchor',
'searchreplace visualblocks code fullscreen',
'insertdatetime media table paste code help wordcount'
],
toolbar:
'undo redo | formatselect | bold italic backcolor | \
alignleft aligncenter alignright alignjustify | \
bullist numlist outdent indent | removeformat | help'
}"
name="content"
:content="post.content"
/>
</div>
<!-- Submit Button -->
<button type="submit" class="btn btn-primary">
Sauvegarder
</button>
</form>
</div>
</template>
<script>
import axios from 'axios'
import { mapGetters } from 'vuex'
import Editor from '#tinymce/tinymce-vue'
export default {
middleware: 'auth',
components: {
'editor': Editor
},
props: ['id'],
data () {
return {
post: {
id: '',
user_id: '',
title: '',
category: '',
image: null,
content: ''
},
path: '/images/post/thumbnail/'
}
},
computed: {
...mapGetters({
user: 'auth/user',
categories: 'categories/categories'
})
},
beforeCreate () {
this.$store.dispatch('categories/fetchCategories')
},
created () {
this.getPostById(this.$route.params.id)
},
methods: {
selectedImage (event) {
this.post.image = event.target.files[0]
},
getPostById (id) {
axios.get('/api/posts/edit/' + id)
.then((response) => {
this.post.id = response.data.id
this.post.user_id = response.data.user_id
this.post.title = response.data.title
this.post.category = response.data.category
this.post.image = response.data.image
this.post.content = response.data.content
})
.catch((error) => {
console.log(error)
})
},
createPost (e) {
this.post.userId = this.user.id
let formData = new FormData(e.target)
let id = this.post.id
formData.append('title', this.post.title)
formData.append('category', this.post.category)
formData.append('image', this.post.image)
formData.append('content', this.post.content)
axios.patch('/api/posts/update/' + id, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then((response) => {
console.log(response)
this.$store.dispatch('posts/fetchPosts')
})
.catch((error) => {
console.log(error)
})
this.$router.push({ name: 'admin' })
}
}
}
</script>
And here the laravel controller PostController#update method
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(PostUpdateRequest $request, $id)
{
$post = Post::findOrFail($id);
$post->update($request->getValidRequest());
return response()->json($request, 200);
}
And the custom validator PostUpdateRequest.php
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'title' => 'required|max:250|unique:posts,title',
'category' => 'required',
'image' => 'mimes:jpg,jpeg,png,bmp',
'content' => 'required'
];
}
public function getValidRequest()
{
$image = $this->file('image');
$slug = Str::slug($this->input('title'));
if (isset($image)) {
$imageExt = $image->getClientOriginalExtension();
$currentDate = Carbon::now()->toDateString();
$imageName = $slug . '-' . $currentDate . '-' . uniqid() . '.' . $imageExt;
if (!Storage::disk('public')->exists('post')) {
Storage::disk('public')->makeDirectory('post');
}
if (!Storage::disk('public')->exists('post/thumbnail')) {
Storage::disk('public')->makeDirectory('post/thumbnail');
}
$path = "images/";
$postImage = Image::make($image)->resize(null, 1060, function ($constraint){
$constraint->aspectRatio();
})->save(public_path($path).'post/'.$imageName);
$thumbnail = Image::make($image)->fit(550, 550)
->save(public_path($path).'post/thumbnail/'.$imageName);
}
return [
'user_id' => Auth::user()->getAuthIdentifier(),
'category_id' => $this->input('category'),
'title' => $this->input('title'),
'slug' => $slug,
'content' => $this->input('content'),
'image' => $imageName,
'is_published' => $this->input('is_published') ?? false,
];
}
The api route in laravel
Route::patch('/update/{id}', 'Backend\PostController#update');
I use practically the same things to store a post, and it work's fine, the only difference is here i pass an id for the post to update and i not use the post method but patch for axios and the route (and i try with put, it's the same error).
thank's for your time !
append '_method' field with value 'PATCH' to formData
formData.append('_method', 'PATCH')
and send axios request post request to update data
axios.post('/api/posts/update/' + id, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})

Resources