How to loop Sweetalert delete confirm into laravel foreach? - laravel

Into Laravel child blade file, I loop foreach users and then use sweetalert to delete into foreach loop.But this sweetalert is working only top row. This is example code just like my code.
<tbody>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
<div class="menu-item px-3">
<form action="{{ route('user.delete', $user->id) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" id="delete-confirm">Delete</button>
</form>
</div>
</td>
</tr>
#endforeach
const button = document.getElementById('delete-confirm');
button.addEventListener('click', e =>{
e.preventDefault();
Swal.fire({
html: `Are you sure you want to delete?`,
icon: "info",
buttonsStyling: false,
showCancelButton: true,
confirmButtonText: "Delete",
cancelButtonText: 'Cancle',
customClass: {
confirmButton: "btn btn-danger",
cancelButton: 'btn btn-primary'
}
}).then(willDel) => {
if(willDel){
form.submit();
}
}
;
});

how about you trying giving delete button unique id, In HTML, the id attribute should be unique for each element on the page. When multiple elements have the same id, it can cause unexpected behavior and may not work as expected. modify your code to use a class instead of an id for your delete buttons:
<tbody>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
<div class="menu-item px-3">
<form action="{{ route('user.delete', $user->id) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="delete-confirm">Delete</button>
</form>
</div>
</td>
</tr>
#endforeach
</tbody>
You can use Javascript to attach the alert to each button as well
$('.delete-confirm').on('click', function(e) {
e.preventDefault();
let form = $(this).closest('form');
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.value) {
form.submit();
}
});
});

Related

Update Column Value with the help of vue js in laravel

This is my blade of laravel
<!-- Main Container -->
<main id="main-container">
<!-- Page Content -->
<div class="content" id="app">
<h2 class="content-heading">Accessory Details</h2>
<div class="block block-themed">
<div class="block-header block-header-default">
<div class="block-options">
<button class="btn btn-success pull-right">New Request</button>
</div>
</div>
<div class="block-content">
<form action="" method="get">
<div class="form-group row">
<label class="col-12" for="example-select2-multiple">Store Location</label>
<div class="col-lg-11">
<select class="form-control" name="store" style="width: 100%;" required>
<option value="">Choose Select Store location..</option>
#foreach($stores as $store)
<option #if($store_selected == $store->id) selected #endif value="{{ $store->id }}">{{ $store->channel_id }} | {{ $store->street_name }}</option>
#endforeach
</select>
</div>
<div class="col-1">
<button type="submit" class="btn btn-alt-success">
Filter
</button>
</div>
</div>
</form>
</div>
</div>
<!-- Dynamic Table Full -->
<div class="block">
<div class="block-content block-content-full">
#include('errors.error')
<div class="table-responsive">
<table class="table table-bordered table-striped table-vcenter js-dataTable-full1" data-page-length='50'>
<thead>
<tr>
<th class="text-center">#</th>
<th class="text-center">User</th>
<th>Store</th>
<th class="">Request Date</th>
<th class="">Status</th>
<th class=""></th>
</tr>
</thead>
<tbody>
#foreach($accessories as $accessory)
<tr>
<td>{{ $accessory->id }}</td>
<td>{{ $accessory->user->name }}</td>
<td>{{ $accessory->store->channel_id }} - {{ $accessory->store->street_name }}</td>
<td>{{ $accessory->request_date }}</td>
<td>{{ $accessory->status }}</td>
<td><button class="btn btn-primary btn-sm" #click="getdetails({{ $accessory->id }})" data-toggle="modal" data-target="#details">Details</button></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
<!-- END Dynamic Table Full -->
<b-modal id="modal-1" title="Details" v-model="dialog" #ok="handleOk">
<form ref="form" #submit.stop.prevent="handleSubmit">
#csrf
{{-- <input type="hidden" v-model="id"/> --}}
<select class="form-control" name="status">
<option>Pending</option>
<option>Ordered</option>
<option>Received</option>
</select>
<br><br>
<table class="table table-bordered">
<tr>
<td>Vendor</td>
<td>Description</td>
<td>QTY</td>
</tr>
<tr v-for="line in lines">
<td>#{{line.name}}</td>
<td>#{{line.description}}</td>
<td>#{{line.qty}}</td>
</tr>
</table>
</form>
</b-modal>
</div>
</main>
<script >
window.app = new Vue({
el: '#app',
mounted: function() {
},
data() {
return {
dialog: false,
lines: [],
}
},
methods: {
getdetails: function(id) {
let self = this;
this.lines = [];
axios.get('/accessory/' + id)
.then(response => {
this.dialog = true;
self.lines = response.data;
console.log(self.lines)
//$(location).attr('href', '/accessory')
})
.catch(function (error) {
alert('Error');
});
},
handleOk(bvModalEvt) {
// Prevent modal from closing
bvModalEvt.preventDefault()
// Trigger submit handler
this.handleSubmit()
},
handleSubmit() {
axios.post('/accessory/status-change/' )
.then(response => {
$(location).attr('href', '/accessory')
})
.catch(function (error) {
alert('Error');
});
}
},
created()
{
}
})
</script>
<script>
$(document).ready(function() {
$('.js-dataTable-full1').DataTable( {
"order": [[ 0, "desc" ]]
} );
});
</script>
Here for the following statement in model , i want to bind it with accessory_request_id which i am recieving {{-- --}}. So what should i select for v-model?
If i check for console.log(self.lines), it returns me an array with accessory_request_id.
Then later on with the help of accessory_reques_id, i want to update status in database.
So follow is my controller code --
{
//return 'test';
//dd($request->all());
$accessory_request = AccessoryRequest::findorfail($request->id);
$accessory_request->status = $request->input('status');
$accessory_request->save();
return ['message' => 'Status Updated'];
}
In web.php -- route is
Route::post('accessory/status-change','AccessoryController#status_change');
please help me to resolve it

Laravel CRUD search function

I need your help that how can i make a search function for my laravel crud system?
I would like to make a search function where admins can search about users name and it works like a filter and after the search only shown the users that equals with the search.
admin.users.index (Blade file):
<div class="col-md-4">
<form action="/search" method="GET">
<div class="input-group">
<input type="search" name="search" class="form-control">
<span class="input-group-btn">
<button type="submit" class="btn btn-primary">Keresés</button>
</span>
</div>
</form>
</div>
<div class="card">
<table class="table">
<thead>
<tr>
<th scope="col">Profilkép</th>
<th scope="col">Név</th>
<th scope="col">Email</th>
<th scope="col">Telefonszám</th>
<th scope="col">Műveletek</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<th scope="row"><img src="/uploads/avatars/{{ $user->avatar }}" style=" width:32x; height:32px; float:left; border-radius:50%; margin-right:25px;"></th>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->phone }}</td>
<td>
<a class="btn btn-sm btn-primary" href=" {{ route('admin.users.edit', $user->id) }}" role="button">Szerkesztés</a>
<button type="button" class="btn btn-sm btn-danger" onclick="event.preventDefault(); document.getElementById('delete-user-form-{{ $user->id }}').submit()">
Törlés
</button>
<form id="delete-user-form-{{ $user->id }}" action="{{ route('admin.users.destroy', $user->id) }}" method="POST" style="display: none;">
#csrf
#method("DELETE")
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
{{ $users->links() }}
</div>
UserController Search function:
public function index(Request $request)
{
if(Gate::denies('logged-in')){
dd('no acces');
}
if(Gate::allows('is-admin')){
return view('admin.users.index', ['users' => User::paginate(10)]);
}
dd("adminnak kell lenned");
$users = User::paginate(10);
return view('admin.users.index')
->with([
'users' => $users
]);
}
public function search(Request $request) {
$search = $request->get('search');
$users = User::table('users')->where('name', 'like', '%'.$search.'%')->paginate(10);
return view('admin', ['users' => $users]);
}
And i dont have route in web.php because i dont know how can i solve this. :(
Please help me!
thank you for your reply!
$('.table').DataTable({
"paging": true,
"pageLength": 10,
"scrollY": 850,
"scrollX": true,
"columnDefs": [{
"targets": -1,
"orderable": false,
},
],
"ordering": false,
});
Put this command to javascript.
add this css
https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css
add this js
https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js
this is datatable search without anything. if you want use this method.

Array is empty when fetching data in template post axios – vuejs

i try to fetch data from an array returned with vuejs script. i displayed data in script and everything is well. in created function, the value array is empty. but with template. the array is empty and not returned null.
export default {
name: 'attribute-values',
props: ['attributeid'],
data() {
return {
values: [],
value: '',
price: '',
currentId: '',
valueTest:'',
addValue: true,
key: 0
}
},
methods: {
loadValues() {
let attributeId = this.attributeid;
var self = this;
self.valueTest='a test';
axios.post('/admin/attributes/get-values', {
id: attributeId
}).then (function(response){
self.values = response.data;
console.log(self.values);
this.values=self.values;
}).catch(function (error) {
console.log(error);
});
console.log(this.values);
}
},
created :function() {
this.loadValues();
}
}
and this is the template
<tr v-if="values.length==0"><td>No items founds</td></tr>
<tr v-for="valuee in values" :key="valuee.id">
<td style="width: 25%" class="text-center">{{ valuee.id }}</td>
<td style="width: 25%" class="text-center">{{ valuee.value }}</td>
<td style="width: 25%" class="text-center">{{ valuee.price }}</td>
<td style="width: 25%" class="text-center">
<button class="btn btn-sm btn-primary">
<i class="fa fa-edit"></i>
</button>
<button class="btn btn-sm btn-danger">
<i class="fa fa-trash"></i>
</button>
</td>
</tr>
this is the output of the array returned from created function:

I am trying to pass user id from my blade template to Vue for Axios post request to the server

However when I click the button only the first button contains the user id the rest returns null. Also depending on where I place my id tag on HTML the data-id is empty. How can I pass data from my blade view to Vue.js for an Axios post request which contains the post Id ?
const app = new Vue({
el: '#like',
data: {
post_id: '',
},
methods: {
whichId: function(event) {
this.post_id = this.$el.getAttribute('data-id');
console.log(this.$el.getAttribute('data-id'));
}
}
})
<div class="container" id="like">
<table class="table mt-5">
<tbody>
#foreach ($posts as $post)
<tr>
<td><img src="images/profil.svg" class="rounded-circle border border-dark ml-2" width="60" height="60" alt=""></td>
<td>{{ $post->username->name }}</td>
<td>{{ $post->content }}</td>
<td>
<button v-on:click="whichId" data-id="{{ $post->id }}">
<img src="/images/heart.svg" width="30" height="30" />
</button>
</td>
<td>{{ $post->created_at->diffForHumans() }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
The this.$el is going to refer to the element. When using PHP to iterate through records. You should pass the id through the click event handler. Thanks to Wilk Randall on laracast for the help.
methods: {
whichId (postId) {
console.log(postId);
}
}
<td><button v-on:click="whichId({{ $post->id }})"<img src="/images/heart.svg" width="30"></button></td>

How to get value from Dynamic Dropdown and submit it in database in VueJs and Laravel

I am creating a form in which you add cities on the basis of countries you get from dynamic drop-down. I am able to get the category_id (foreign key) in Vuejs but I don't how to pass it to the laravel back-end. I want to create a subcategory object with name and category_id. category_id is foreign key. I am unable to get category_id and it is passing NULL to db.
**Category = Country**
**Subcategory = City**
<template id="add-post">
<div>
<table class="table">
<thead>
<tr>
<th>#</th>
<th>City Name</th>
<th>Country id</th>
</tr>
</thead>
<tbody>
<tr v-for="(subcategory, index) in citylist" :key="subcategory.id">
<td>{{ index + 1 }}</td>
<td>{{ subcategory.name }}</td>
<td>{{ subcategory.category_id }}</td>
</tr>
</tbody>
</table>
<h3>Add City</h3>
<form v-on:submit.prevent = "createPost">
<select v-model="countryid" name="country" class="form-control" #change="myFunction()">
<option countryid disabled>Select Country</option>
<option v-for="category in categories" v-bind:value='category.id' v-text="category.name">{{category.name}}</option>
</select>
<div class="form-group">
<label for="add-name">Name</label>
<input v-model="subcategory.name" class="form-control" required />
</div>
<button type="submit" class="btn btn-xs btn-primary">Add City</button>
<!-- <button v-on:click="setPostId()">click</button> -->
<router-link class="btn btn-xs btn-warning" v-bind:to="'/'">Cancel</router-link>
</form>
</div>
</template>
<script>
export default {
data: function () {
return {
categories: [],
category: '',
countryid:'',
subcategories: [],
subcategory: {name: '', category_id: ''}
};
},
mounted(){
this.loadCategories()
},
created: function() {
let uri = 'http://localhost:8000/cities/';
Axios.get(uri).then((response) => {
this.subcategories = response.data;
});
},
computed: {
citylist: function(){
if(this.subcategories.length) {
return this.subcategories;
}
}
},
methods: {
myFunction: function() {
console.log(this.countryid)
},
loadCategories(){
axios.get('/api/categories')
.then(response => this.categories = response.data)
.catch(error => console.log(error))
},
createPost: function() {
let uri = 'http://localhost:8000/addsubcategory/';
Axios.post(uri, this.subcategory).then((response) => {
this.$router.push({name: 'City'})
})
}
}
}
</script>
you can make drop down
<select v-model="fruit" id="deptList">
<option v-for="company_master in company_masters.data" v-bind:value="company_master.CompanyId"> {{company_master.CompanyName}}
</option>
</select>
and call the data with axios like
axios.get("api/company_master").then(response => (this.company_masters = response.data));
also define
company_masters:[],
fruit:'',

Resources