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

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.

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))
},
}

Return errors in server side validation with Laravel and Vue

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.

data not stored in laravel back end from axios post of vue js front end

I have some data that i need to store in my database coming from localStorage. One is an input field where a user can change the quantity of an item, the other is a radio box where the user has to select an address to deliver to. The issue is that it just won't store the address_id in my database nor update the qty field of the input in my cart. Could someone take a look at it and explain why this doesn't work? I'd appreciate it so much thanks!
Note: The data object is reactive, I checked in my vue dev tools and it changes the data correclty so no issue there.
Vue add to cart button component:
<template>
<form #submit.prevent="addToCart">
<button>Add to cart</button>
</form>
</template>
<script>
export default {
props: ['productId', 'categoryId'],
data() {
return {
product: {},
cart: []
}
},
methods: {
fetchData() {
axios.get(`http://localhost:8000/api/product/${this.productId}/category/${this.categoryId}`)
.then(res => {
const { product } = res.data;
this.product.id = product.id
this.product.title = product.title;
this.product.fitSize = product.fit_size;
this.product.jeansSize = product.jeans_size;
this.product.price = product.price;
this.product.img = product.images[0].images;
this.product.quantity = 1;
})
.catch(err => console.log(err))
},
addToCart() {
if(localStorage.getItem('cart')) {
// Little note to myself:
// Grab data from local storage and turn it into a js array of objects
// Push new product to that array every time the addToCart method gets fired
// get that array with the additional items and store back in local storage as a JSON string
let cart = JSON.parse(localStorage.getItem('cart'));
cart.push(this.product)
return localStorage.setItem('cart', JSON.stringify(cart))
} else {
this.cart.push(this.product)
localStorage.setItem('cart', JSON.stringify(this.cart))
}
}
},
mounted() {
this.fetchData()
}
}
</script>
Vue checkout component:
<template>
<div>
<div v-for="product in products" v-bind:key="product.id">
<p>Img: {{product.img}}</p>
<p>Title: {{product.title}}</p>
<p>Price: {{product.price}}</p>
<input v-model="product.quantity" type="number" name="qty" id="qty">
<br>
</div>
<form method="POST" #submit.prevent="placeOrder">
<div v-for="address in user.addresses" v-bind:key="address.id">
<input type="radio" v-model="addressId" v-bind:value="address.id" name="address_id" id="address_id">{{address.street}}
</div>
<button>Place order</button>
</form>
</div>
</template>
<script>
export default {
props: ['user'],
data() {
return {
products: null,
addressId: null,
orders: [],
}
},
methods: {
fetchDataFromLocalStorage() {
this.products = JSON.parse(localStorage.getItem('cart'))
},
createOrders() {
this.products.forEach(product => {
this.orders.push({
qty: product.quantity,
user_id: this.user.id,
product_id: product.id,
address_id: this.addressId
})
})
},
placeOrder() {
const sendOrders = { orders: this.orders }
axios.post(`http://localhost:8000/api/user/${this.user.id}/checkout`, sendOrders)
.then(res => console.log(res.data))
.catch(err => console.log(err))
},
},
mounted() {
this.fetchDataFromLocalStorage();
this.createOrders();
}
}
</script>
Laravel store method:
public function store(Request $request, $id)
{
foreach ($request->orders as $order) {
Order::create([
'qty' => $order['qty'],
'product_id' => $order['product_id'],
'user_id' => $order['user_id'],
'address_id' => $order['address_id']
]);
}
return response()->json('Order created');
}
Order model:
class Order extends Model
{
protected $guarded = [];
public function product()
{
return $this->hasOne(Product::class);
}
public function user()
{
return $this->belongsTo(Order::class);
}
public function addresses()
{
return $this->hasOne(Addresses::class);
}
}
Laravel api route:
Route::post('/user/{id}/checkout', 'CheckoutController#store');
Tinker when I make a post request:
App\Order {#3072
id: "127",
qty: "1", // Default value just won't change whenever I try to update it!
delivered: "0",
product_id: "3", // This works
created_at: "2019-12-23 10:08:09",
updated_at: "2019-12-23 10:08:09",
user_id: "1", // This works
address_id: null, // This doesn't
},
],

Vue multiselect not getting id and name

I have used vue multiselect in my form and I have made the options dynamic as autocomplete by axios post . I am returning only id and name from the controller to js file but it is displaying all the properties of option
This is My form
<multiselect v-model="form.books" :options="options" :loading="isLoading" :internal-search="false" #search-change="getData" :multiple="true" :close-on-select="false" :hide-selected="true" :limit="5" :internal-search="false"></multiselect>
This is my vue js file
Vue.component('coupon-form', {
mixins: [AppForm],
data: function() {
return {
form: {
name: '' ,
description: '' ,
valid_from: '' ,
valid_till: '' ,
discount: '' ,
enabled: false,
books:[],
},
isLoading: false,
options: [],
}
},
methods: {
getData(query){
this.isLoading = true;
axios.post('/admin/books/find/'+query)
.then((response) => {
console.log(response);
this.options = response.data;
this.isLoading = false;
})
.catch((error) => {
this.isLoading = false;
});
}
}
});
This is my controller
public function find($books)
{
$search = $books;
$books = Book::select('id','name')
->where('id','like',"%$search%")
->orWhere('name','like',"%$search%")
->orWhere('sku','like',"%$search%")
->orWhere('sale_price','like',"%$search$")
->limit(5)->get();
return $books;
}
}
As we can see I am selecting the id and name of the Book Model but I am getting many properties of Book like this
And I want to show the name in the options and in the v-model I want to have id
How to do that
You need new field in your data and watcher for value so try something like this:
<multiselect v-model="selected"...></multiselect>
data () {
selected: []
...
},
watch: {
selected (newValues) {
this.form.books = newValues.map(obj => obj.id)
}
}
I think that is what you need.
I found a lot of issues about that and package doesn't have prop for that.
You can read more on there: link1, link2
Good luck!
DB::table('books')->select('id,name')->where('id','like',"%$search%")
->orWhere('name','like',"%$search%")
->orWhere('sku','like',"%$search%")
->orWhere('sale_price','like',"%$search$")
->limit(5)->get();
<template>
<div>
<multiselect v-model="yourForm.bindThis" :options="options" :custom-label="showItems" placeholder="Select one" :label="options.name_of_a_column_from_record" :track-by="options.id_of_record" :multiple="true"></multiselect>
</div>
</template>
<script>
import Multiselect from 'vue-multiselect';
data(){
return{
options: [],
yourForm: {
bindThis: '',
}
}
},
methods:{
showItems({data}){
return `${data.name_of_a_column_from_record}`;
}
}
</script>
Let me know if it did the magic
Add track-by and label props.
<multiselect
v-model="form.users"
:options="scholars"
:multiple="true"
:searchable="true"
label="name"
track-by="id"
>
</multiselect>

Resources