Return errors in server side validation with Laravel and Vue - laravel

I'm trying to return the errors in server side validation so the user can know which error they have, but I don't know how to return something that it is understandable for a normal person.
Here's my front-end
<v-form>
<v-row>
<v-col cols="12" sm="6" md="6">
<v-text-field label="Serial Number" v-model="plane.serial_number" color="black" counter="30"></v-text-field>
</v-col>
</v-row>
<v-btn color="yellow" class="black-text" #click="add()">Submit</v-btn>
</v-form>
<script>
import Swal from 'sweetalert2'
export default {
data() {
return {
errors: [],
plane: {
serial_number: '',
},
}
},
methods: {
add() {
const params = {
serial_number: this.plane.serial_number,
};
axios.post(`/planes`, params)
.then(res => {
Swal.fire({
title: 'Success!',
html: 'Plane created successfully!',
icon: 'success',
confirmButtonText: 'OK',
})
}).catch(e => {
this.errors = e;
console.log(this.errors);
Swal.fire({
title: 'Error!',
icon: 'error',
})
})
},
}
}
</script>
Back-end
public function store(Request $request)
{
$this->validate($request, [
'serial_number' => ['required','string', 'unique:airplanes']
]);
$airplane = new Airplane();
$airplane->serial_number = $request->serial_number;
$airplane->save();
}
The console.log isn't returning anything at all.

In this.errors if you output this.errors.message you should see a friendly message. Hope that helps! ... You can also dig into the this.errors.response object which has things like the headers and status.

Related

nuxt,js vue,js how to fetch data inside of table

i am new in vuetify and nuxt.js
i am getting data from database but i want to show that in vuetify table.
Laravel API Controller
public function businesslist() {
$businesslist = Business::paginate(2)->toJson(JSON_PRETTY_PRINT);
return response($businesslist);
}
}
MY Laravel API
Route::get('/businesslist', 'BusinessController#userlist')->name('businesslist');
MY Nuxt.js vue page
<template>
<v-card>
<v-card-title>
Nutrition
<v-spacer></v-spacer>
<v-text-field
v-model="search"
append-icon="mdi-magnify"
label="Search"
single-line
hide-details
></v-text-field>
</v-card-title>
<v-data-table
:headers="headers"
:items="businessuser"
:search="search"
></v-data-table>
</v-card>
</template>
<script>
export default {
data() {
return {
search: '',
headers: [{
text: 'Name',
value: 'name'
},
{
text: 'Mobile ',
value: 'mobile_number'
},
{
text: 'Location ',
value: 'location'
},
{
text: 'Join Date ',
value: 'registration_date'
},
{
text: 'Renewal Date ',
value: 'registration_renewal_date'
},
],
businessuser: [
],
}
},async asyncData({$axios}) { let {data} = await $axios.$get('/businesslist')
return {
businesslist: data
} },
}
}
</script>
You should use created event, in this event, call your businesslist API and in the response, you should assign received data to your businessuser vue js variable.
Let see here one example.
created () {
this.initialize();
},
methods: {
initialize () {
this.businessuser = businesslistApiCalling();
}
}
businesslistApiCalling(); is just an example you should call here the API method to receive Json data from the Server.

How to display records from Laravel via Vuetify v-data-table component

I have a project build in Laravel with Vue.js which work perfect statically, but I need convert it into dynamically to pull records from database table to v-data-table component.
I know Laravel and I know How these things works via Ajax/jQuery but I'm pretty new in Vue.js
Can someone explain to me how to display the results from the database in the v-data-table component.
Thanks.
Here is the Vue.js file:
<template>
<v-app>
<v-main>
<div>
<v-tab-item>
<v-card flat>
<v-card-text>
<v-card-title>
<v-spacer></v-spacer>
<v-text-field
v-model="search"
append-icon="mdi-magnify"
label="Search"
single-line
hide-details
></v-text-field>
</v-card-title>
<v-data-table
:headers="headers"
:items="items"
:items-per-page="5"
class=""
:search="search">
</v-data-table>
</v-card-text>
</v-card>
</v-tab-item>
</div>
</v-main>
</v-app>
</template>
<script>
export default {
data: () => ({
search: '',
items: [],
headers: [
{
text: '#',
align: 'start',
sortable: false,
value: 'id',
},
{ text: 'Name', value: 'name' },
{ text: 'Slug', value: 'slug' },
],
/*THIS IS A STATIC DATA*/
// items: [
// {
// id: 1,
// name: 'Test Name 1',
// slug: 'test-name-1',
// },
// {
// id: 2,
// name: 'Test Name 2',
// slug: 'test-name-2',
// },
// ],
/*THIS IS A STATIC DATA*/
}),
created () {
this.getItems();
},
methods: {
getItems() {
axios
.get('/test/vue')
.then((response) => {
this.items = response.data,
console.log(response.data)
})
.catch(error => console.log(error))
},
}
}
</script>
And Here is Blade file:
#extends('it-pages.layout.vuetify')
#section('content')
<div id="appContainer">
<software-template></software-template>
</div>
Output in the console is :
console.log
Response from axios is also Ok
response
My Controller :
public function showData()
{
$items = Category::select('id', 'name', 'slug')->where('order', 1)->get();
// dd($items);
return response()->json(['items' => $items]);
}
My route:
Route::get('test/vue', 'PagesController#showData');
console.log after changes axios lines
console-log
So there were multiple issues here:
The backend did you return a correct array
The frontend performed a post request instead of a get
The this context is not correct since you are using a function instead of arrow syntax
Make sure to look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions and read about how this changes how this is elevated.
In your case, you need to change the code on the then part of your axios call:
.then((response) => {
this.items = response.data
})
I must to say that I solve the problem.
Problem was been in axios response.
Instead this.items = response.data I change to this.items = response.data.items and it work perfectly.
methods: {
getItems() {
axios
.get('/test/vue')
.then((response) => {
this.items = response.data.items
console.log(response.data.items)
})
.catch(error => console.log(error))
},
}

Unable to insert data in the database in laravel projet with vuejs and vuetify

I have setup a laravel project with Vuejs and vuetify to insert data in the database. But for some reason I not able to insert data in the database. When I compile my code I can see no error but when I inspect my code I can see error in my console saying "Internal service error" . I assuming that the error may be in my controller.
Here are m code:
Location.vue
<template>
<v-app id="inspire">
<v-data-table
item-key="code"
class="elevation-1"
color="error"
:loading = "loading"
loading-text="Loading... Please wait"
:headers="headers"
:options.sync="options"
:server-items-length="locations.total"
:items="locations.data"
show-select
#input="selectAll"
:footer-props="{
itemsPerPageOptions: [5,10,15],
itemsPerPageText: 'Roles Per Page',
'show-current-page': true,
'show-first-last-page': true
}"
>
<template v-slot:top>
<v-toolbar flat color="dark">
<v-toolbar-title>My Stage</v-toolbar-title>
<v-divider
class="mx-4"
inset
vertical
></v-divider>
<v-spacer></v-spacer>
<v-dialog v-model="dialog" max-width="500px">
<template v-slot:activator="{ on }">
<v-btn color="error" dark class="mb-2" v-on="on">Add New Stage</v-btn>
<v-btn color="error" dark class="mb-2 mr-2" #click="deleteAll">Delete</v-btn>
</template>
<v-card>
<v-card-title>
<span class="headline">{{ formTitle }}</span>
</v-card-title>
<v-card-text>
<v-container>
<v-row>
<v-col cols="12" sm="12" >
<v-text-field autofocus color="error" v-model="editedItem.code" label="Code"></v-text-field>
</v-col>
<v-col cols="12" sm="12" >
<v-text-field autofocus color="error" v-model="editedItem.name" label="Name"></v-text-field>
</v-col>
<v-col cols="12" sm="12" >
<v-text-field autofocus color="error" v-model="editedItem.description" label="Description"></v-text-field>
</v-col>
</v-row>
</v-container>
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color="error darken-1" text #click="close">Cancel</v-btn>
<v-btn color="error darken-1" text #click="save">Save</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-toolbar>
<v-row>
<v-col cols="12">
<v-text-field #input="searchIt" label="Search..." class="mx-4" ></v-text-field>
</v-col>
</v-row>
</template>
<template v-slot:item.action="{ item }">
<v-icon
small
class="mr-2"
#click="editItem(item)"
>
mdi-content-save-edit-outline
</v-icon>
<v-icon
small
#click="deleteItem(item)"
>
mdi-delete
</v-icon>
</template>
<template v-slot:no-data>
<v-btn color="error" #click="initialize">Reset</v-btn>
</template>
</v-data-table>
<v-snackbar v-model="snackbar" >
{{text}}
<v-btn
color="error"
text
#click="snackbar = false"
>
Close
</v-btn>
</v-snackbar>
</v-app>
</template>
<script>
export default {
data: () => ({
dialog: false,
loading: false,
snackbar: false,
selected: [],
text: '',
options:{
itemsPerPage: 5,
sortBy:['id'],
sortDesc: [false]
},
headers: [
{text: '#',align: 'left', sortable: false,value: 'id'},
{ text: 'Code', value: 'code' },
{ text: 'Name', value: 'name' },
{ text: 'Description', value: 'description' },
{ text: 'Actions', value: 'action'},
],
locations: [],
editedIndex: -1,
editedItem: {
id: '',
code: '',
name: '',
description: '',
},
defaultItem: {
id: '',
code: '',
name: '',
description: '',
},
}),
computed: {
formTitle () {
return this.editedIndex === -1 ? 'New Stage' : 'Edit Stage'
},
},
watch: {
dialog (val) {
val || this.close()
},
options:{
handler(e){
console.dir(e);
const sortBy = e.sortBy.length>0 ? e.sortBy[0].trim() : 'id';
const orderBy = e.sortDesc[0] ? 'desc' : 'asc';
axios.get(`/api/locations`,{params:{'page':e.page, 'per_page':e.itemsPerPage, 'sort_by': sortBy, 'order_by': orderBy}})
.then(res => {
this.locations = res.data.locations
})
},
deep: true
}
},
created () {
this.initialize()
},
methods: {
selectAll(e){
this.selected = [];
if(e.length > 0){
this.selected = e.map(val => val.id)
}
},
deleteAll(){
let decide = confirm('Are you sure you want to delete these items?')
if(decide){
axios.post('/api/locations/delete', {'locations': this.selected})
.then(res => {
this.text = "Records Deleted Successfully!";
this.selected.map(val => {
const index = this.locations.data.indexOf(val)
this.locations.data.splice(index, 1)
})
this.snackbar = true
}).catch(err => {
console.log(err.response)
this.text = "Error Deleting Record"
this.snackbar=true
})
}
},
searchIt(e){
if(e.length > 3){
axios.get(`/api/locations/${e}`)
.then(res => this.locations = res.data.locations)
.catch(err => console.dir(err.response))
}
if(e.length<=0){
axios.get(`/api/locations`)
.then(res => this.locations = res.data.locations)
.catch(err => console.dir(err.response))
}
},
paginate(e){
const sortBy = e.sortBy.length>0 ? e.sortBy[0].trim() : 'code';
const orderBy = e.sortDesc[0] ? 'desc' : 'asc';
axios.get(`/api/locations`,{params:{'page':e.page, 'per_page':e.itemsPerPage, 'sort_by': sortBy, 'order_by': orderBy}})
.then(res => {
this.locations = res.data.locations
})
},
initialize () {
// Add a request interceptor
axios.interceptors.request.use((config) => {
this.loading = true;
return config;
}, (error) => {
this.loading = false;
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use( (response) => {
this.loading = false;
return response;
}, (error) => {
this.loading = false
return Promise.reject(error);
});
},
editItem (item) {
this.editedIndex = this.locations.data.indexOf(item)
this.editedItem = Object.assign({}, item)
this.dialog = true
},
deleteItem (item) {
const index = this.locations.data.indexOf(item)
let decide = confirm('Are you sure you want to delete this item?')
if(decide){
axios.delete('/api/locations/'+item.id)
.then(res => {
this.text = "Record Deleted Successfully!";
this.snackbar = true
this.locations.data.splice(index, 1)
}).catch(err => {
console.log(err.response)
this.text = "Error Deleting Record"
this.snackbar=true
})
}
},
close () {
this.dialog = false
setTimeout(() => {
this.editedItem = Object.assign({}, this.defaultItem)
this.editedIndex = -1
}, 300)
},
save () {
if (this.editedIndex > -1) {
const index = this.editedIndex
axios.put('/api/locations/'+this.editedItem.id, {'code': this.editedItem.code, 'name': this.editedItem.name, 'description': this.editedItem.description})
.then(res => {
this.text = "Record Updated Successfully!";
this.snackbar = true;
Object.assign(this.locations.data[index], res.data.location)
})
.catch(err => {
console.log(err.response)
this.text = "Error Updating Record"
this.snackbar=true
})
// Object.assign(this.locations[this.editedIndex], this.editedItem)
} else {
axios.post('/api/locations',{'code': this.editedItem.code, 'name': this.editedItem.name, 'description': this.editedItem.description})
.then(res => {
this.text = "Record Added Successfully!";
this.snackbar=true;
this.locations.data.push(res.data.location)
})
.catch(err => {
console.dir(err.response)
this.text = "Error Inserting Record"
this.snackbar=true
})
}
this.close()
},
},
}
</script>
<style scoped></style>
Location.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Location extends Model
{
protected $guarded = [];
}
LocationController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Location;
class LocationController extends Controller
{
public function index(Request $request)
{
$per_page = $request->per_page ? $request->per_page : 5;
$sort_by = $request->sort_by;
$order_by = $request->order_by;
return response()->json(['locations' => Location::orderBy($sort_by, $order_by)->paginate($per_page)],200);
}
public function store(Request $request)
{
$location= Location::create([
'code' =>$request->code
'name' =>$request->name
'description' =>$request->description
]);
return response()->json(['location'=>$location],200);
}
public function show($id)
{
$locations = Location::where('code', 'name','description''LIKE', "%$id%")->paginate();
return response()->json(['locations' => $locations],200);
}
public function update(Request $request, $id)
{
$location = Location::find($id);
$location->code = $request->code;
$location->name = $request->name;
$location->description = $request->description;
$location->save();
return response()->json(['location'=>$location], 200);
}
public function destroy($id)
{
$location = Location::find($id)->delete();
return response()->json(['location'=>$location],200);
}
public function deleteAll(Request $request){
Location::whereIn('id', $request->locations)->delete();
return response()->json(['message', 'Records Deleted Successfully'], 200);
}
}
yeah, the issue in your LocationController.php file, you missed commas in Location::create . Also, show function has a problem. notice carefully.
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Location;
class LocationController extends Controller
{
public function index(Request $request)
{
$per_page = $request->per_page ? $request->per_page : 5;
$sort_by = $request->sort_by;
$order_by = $request->order_by;
return response()->json(['locations' => Location::orderBy($sort_by, $order_by)->paginate($per_page)],200);
}
public function store(Request $request)
{
$location= Location::create([
'code' =>$request->code,
'name' =>$request->name,
'description' =>$request->description
]);
return response()->json(['location'=>$location],200);
}
public function show($id)
{
$locations = Location::where('code','LIKE', "%$id%")->orWhere('name','LIKE', "%$id%")->orWhere('description', 'LIKE', "%$id%")->paginate();
return response()->json(['locations' => $locations],200);
}
public function update(Request $request, $id)
{
$location = Location::find($id);
$location->code = $request->code;
$location->name = $request->name;
$location->description = $request->description;
$location->save();
return response()->json(['location'=>$location], 200);
}
public function destroy($id)
{
$location = Location::where('id', $id)->delete();
return response()->json(['location'=>$location],200);
}
public function deleteAll(Request $request){
Location::whereIn('id', $request->locations)->delete();
return response()->json(['message', 'Records Deleted Successfully'], 200);
}
}

Auto fill input field after Select dropdown list [ Laravel, Vuejs ]

I want to create something that search in Product table and i select in dropdown its will display data in order table like pic below?
how can i archieve that? Anyone give me any hint?
thanks in advances...
In my Vuetify
i used vue-select package
<v-col md="6" cols="12">
<label class="font-weight-bold">Select Product</label>
<v-select v-model="search" label="name" :options="purchases"></v-select>
</v-col>
In my script file
<script>
export default {
created() {
this.fetchData()
},
data() {
return {
form: {},
search: '',
items: [],
purchase_status: ['Received', 'Partial', 'Pending', 'Ordered'],
}
},
methods: {
fetchData() {
this.$axios.$get(`api/product`)
.then(res => {
this.items = res.data;
console.log(this.items)
})
.catch(err => {
console.log(err)
})
},
uploadFile(event) {
const url = 'http://127.0.0.1:3000/product/add_adjustment';
let data = new FormData();
data.append('file', event.target.files[0]);
let config = {
header: {
'content-Type' : 'image/*, application/pdf'
}
}
this.$axios.$post(url,data,config)
.then(res => {
console.log(res);
})
}
}
}
</script>
When you select a product in the dropdown, you'll get product_id. Use this product_id and call API to get data for the orders table.

Select Box is not changing immediately after changing input in ElementUi Vue

I have made a CRUD based admin pannel with laravue. Now my problem is that whenever I am on the update page, I can't change the category immediately. I always have to make change in some other field to view the changed category. Its working fine on add card page when all the fields are empty.
This is the video of my issue
https://thisisntmyid.tumblr.com/post/189075383873/my-issue-with-elementui-and-laravue-and-vue
I've included the code for my list page as well as the add/update page.
Code for the listing page that will lead u to edit page
<div class="app-container">
<h1>My Cards</h1>
<Pagination
:total="totalCards"
layout="total, prev, pager, next"
:limit="10"
:page.sync="currentPage"
#pagination="loadNewPage"
></Pagination>
<el-table v-loading="loadingCardsList" :data="cards" stripe style="width: 100%">
<el-table-column prop="name" sortable label="Product Name"></el-table-column>
<el-table-column prop="description" label="Description" width="200px"></el-table-column>
<el-table-column prop="price" label="Price"></el-table-column>
<el-table-column prop="cardcategory" sortable label="Category"></el-table-column>
<el-table-column label="Operations" width="300px">
<template slot-scope="scope">
<el-button size="mini" type="primary" #click="handleView(scope.$index, scope.row)">View</el-button>
<el-button size="mini" #click="handleEdit(scope.$index, scope.row)">Edit</el-button>
<el-button size="mini" type="danger" #click="handleDelete(scope.$index, scope.row)">Delete</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog :visible.sync="viewCard" width="30%">
<el-card class="box-card">
<h1>{{currentViewedCard.name}}</h1>
<p>{{currentViewedCard.description}}</p>
<p>{{currentViewedCard.price}}</p>
<el-tag>{{currentViewedCard.cardcategory}}</el-tag>
</el-card>
</el-dialog>
</div>
</template>
<script>
import Resource from '#/api/resource';
import Pagination from '#/components/Pagination/index.vue';
const cardcategoryResource = new Resource('cardcategories');
const cardResource = new Resource('cards');
export default {
name: 'Cards',
components: {
Pagination,
},
data() {
return {
cards: [],
categories: [],
currentPage: '',
totalCards: '',
loadingCardsList: true,
currentViewedCard: '',
viewCard: false,
};
},
created() {
this.getCardCategories();
this.getCardList({ page: 1 });
},
methods: {
async getCardList(query) {
this.loadingCardsList = true;
const data = await cardResource.list(query);
this.cards = data.data;
for (const card of this.cards) {
card['cardcategory'] = this.getCategoryName(card.cardCategory_id);
}
console.log(this.cards);
this.totalCards = data.total;
this.loadingCardsList = false;
},
async getCardCategories() {
this.categories = await cardcategoryResource.list({});
console.log(this.categories);
},
loadNewPage(val) {
this.getCardList({ page: val.page });
},
getCategoryName(id) {
return this.categories[id - 1].name;
},
handleView(index, info) {
this.viewCard = true;
this.currentViewedCard = info;
},
handleEdit(index, info) {
this.$router.push('/cards/edit/' + info.id);
},
closeDialog() {
this.viewProduct = false;
this.currentProductInfo = null;
},
handleDelete(index, info) {
cardResource.destroy(info.id).then(response => {
this.$message({
message: 'Card Deleted Successfully',
type: 'success',
duration: 3000,
});
this.getCardList({ page: this.currentPage });
});
},
},
};
</script>
<style lang="scss" scoped>
</style>
Code for the add/update page
<template>
<div class="app-container">
<el-form ref="form" :model="formData" label-width="120px">
<el-form-item label="Name">
<el-input v-model="formData.name"></el-input>
</el-form-item>
<el-form-item label="Description">
<el-input type="textarea" v-model="formData.description"></el-input>
</el-form-item>
<el-form-item label="Price">
<el-input v-model="formData.price"></el-input>
</el-form-item>
<el-form-item label="Category">
<!-- DO something here like binding category id to category name sort of meh... -->
<el-select v-model="formData.cardcategory" placeholder="please select category">
<el-option v-for="item in categories" :key="item" :label="item" :value="item"></el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" #click="editable ? updateProduct() : createProduct()">Save</el-button>
<el-button #click="editable ? populateFormData($route.params.id) : formDataReset()">Reset</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import Resource from '#/api/resource';
const cardcategoryResource = new Resource('cardcategories');
const cardResource = new Resource('cards');
export default {
data() {
return {
formData: {
name: '',
description: '',
price: '',
cardcategory: '',
},
categories: [],
editable: '',
};
},
created() {
this.getCategories();
if (this.$route.params.id) {
this.editable = true;
this.populateFormData(this.$route.params.id);
} else {
this.editable = false;
}
},
methods: {
async getCategories() {
this.categories = (await cardcategoryResource.list({})).map(
cat => cat.name
);
console.log(this.categories);
},
formDataReset() {
this.formData = {
name: '',
description: '',
price: '',
cardcategory: '',
};
},
populateFormData(id) {
cardResource.get(id).then(response => {
this.formData = Object.assign({}, response);
this.formData.price = this.formData.price.toString();
this.formData.cardcategory = this.categories[
this.formData.cardCategory_id - 1
];
delete this.formData.cardCategory_id;
});
},
filterFormData(formData) {
const cardData = Object.assign({}, formData);
cardData['cardCategory_id'] =
this.categories.indexOf(cardData.cardcategory) + 1;
delete cardData.cardcategory;
return cardData;
},
createProduct() {
const cardData = this.filterFormData(this.formData);
cardResource
.store(cardData)
.then(response => {
this.$message({
message: 'New Card Added',
type: 'success',
duration: 3000,
});
this.formDataReset();
})
.catch(response => {
alert(response);
});
},
updateProduct() {
const cardData = this.filterFormData(this.formData);
cardResource.update(this.$route.params.id, cardData).then(response => {
this.$message({
message: 'Card Updated Successfully',
type: 'success',
duration: 3000,
});
this.populateFormData(this.$route.params.id);
});
},
},
};
</script>
<style>
</style>
Update
here is the git hub repo for my project
https://github.com/ThisIsntMyId/laravue-admin-pannel-demo

Resources