problem in datatable when use in livewire component - laravel

i use livewire defer loading for load data after rendering page.
After opening the page, the information is successfully received and displayed in the table
But the problem is that I use datatable and when the received information is displayed, datatable becomes a simple table. As if I did not use datatable at all.
This is the livewire component code
class Cryptolist extends Component
{
public bool $loadData = false;
public function init()
{
$this->loadData = true;
}
public function render()
{
try {
if ($this->loadData) {
$api = new \Binance\API('api','secret');
$prices = $api->coins();
$one = json_encode($prices, true);
$coins = json_decode($one , true);
} else {
$coins = [];
}
return view('livewire.backend.crypto.cryptolist')->with('coins' , $coins);
}catch(\Exception $e)
{
return view('wrong')->with('e' , $e);
}
}
}
And this is the component view where the table is located and displays the received information
<div wire:init="init">
#if ($loadData)
<div id="loadesh1" wire:ignore>
<table class="datatable-init nk-tb-list nk-tb-ulist" data-auto-responsive="false">
<thead>
<tr class="nk-tb-item nk-tb-head">
<th class="nk-tb-col"><span class="sub-text">name</span></th>
<th class="nk-tb-col tb-col-mb"><span class="sub-text">balance</span></th>
</tr>
</thead>
<tbody>
#foreach ($coins as $item => $value)
<tr class="nk-tb-item">
<td class="nk-tb-col">
<div class="user-card">
<div class="user-avatar d-none d-sm-flex">
#if(file_exists(public_path() . '/img/crypto/'.strtolower($value['coin'].".svg")))
<img style="border-radius: 0"
src="{{asset('/img/crypto/'.strtolower($value['coin']))}}.svg" class="img-fluid"
alt="">
#else
<img style="border-radius: 0"
src="https://demo.rayanscript.ir/-/vendor/cryptocurrency-icons/32/color/noimage.png"
class="img-fluid" alt="">
#endif
</div>
<div class="user-info">
<span class="tb-lead english" style="font-weight: bolder">{{$value['name']}}</span>
<span class="english">{{$value['coin']}}</span>
</div>
</div>
</td>
<td class="nk-tb-col tb-col-mb" data-order="{{$value['coin']}}">
<div class="btn-group" aria-label="Basic example">
<button type="button" class="btn btn-sm btn-dim btn-light"
wire:click="getBalance('{{$value['coin']}}')">
<div wire:loading wire:target="getBalance('{{$value['coin']}}')">
<span class="spinner-border spinner-border-sm" role="status"
aria-hidden="true"></span>
</div>
<span class="w-120px" id="coin-{{$value['coin']}}">get balance</span>
</button>
<button type="button" class="btn btn-sm btn-dim btn-primary">add coin</button>
</div>
</td>
</tr><!-- .nk-tb-item -->
#endforeach
</tbody>
</table>
</div>
#else
Loading data...
#endif
</div>
What do you think is the problem, what code is written incorrectly?

Related

Why Does Image Read Null When I Try To Delete My Category?

I am trying to find a way to delete my category that I have created. I have the image stored in my public folder and I get the error attempt to read image is null, I think the error has to do with category_id being null. How can I retrieve it for my category object?
//Controller class
class Index extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $category_id;
//setting category_id
public function deleteCategory($category_id)
{
$this->category_id = $category_id;
}
public function destroyCategory() {
$category = Category::find($this->category_id);
// dd($this);
$path = 'uploads/category/'.$category->image;
if (File::exists($path)) {
File::delete($path);
}
$category->delete();
session()->flash('message', 'Category Deleted');
$this->dispatchBrowserEvent('close-modal');
}
public function render()
{
$categories = Category::orderBy('id', 'DESC')->paginate(10);
return view('livewire.admin.category.index', ['categories' => $categories]);
}
}
this is my component blades file that accompanies it.
//my blade file
<div>
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Category Delete</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form wire:submit.prevent="destroyCategory">
<div class="modal-body">
<h6>Are you sure you want to delete this data?</h6>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Yes. Delete</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
#if(session('message'))
<div class="alert alert-success">{{session('message')}}</div>
#endif
<div class="card-header">
<h4>
Category
Add Category
</h4>
</div>
<div class="card-body">
{{-- display all categories using livewire --}}
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($categories as $category)
<tr>
<td>{{$category->id}}</td>
<td>{{$category->name}}</td>
<td>{{$category->status == '1' ? "Hidden" : "Visible"}}</td>
<td>
Edit
<a href="#" wire:click="deleteCategory({{$category->id}})" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
Delete
</a>
</tr>
#endforeach
</tbody>
</table>
<div>
{{$categories->links()}}
</div>
</div>
</div>
</div>
</div>
#push('script')
<script>
window.addEventListener('close-modal', event => {
$('#deleteModal').modal('hide');
})
</script>
#endpush
I wanted to add my sugestion as a comment, however is to long and it doesn't look good when i add the code, so i need to add a post.
I see that you are using deleteCategory() to get category_id and set it on a public varaible public $category_id;, when you get the variable then you try to delete the category with destroyCategory().
If that is true you don't need to create 2 functions for that,
so instead try and use this:
public function deleteCategory($category_id) {
$category = Category::find($category_id);
$path = 'uploads/category/'.$category->image;
// dd($path); <- try this on the debbuger, to see the path
if (File::exists($path)) {
File::delete($path);
}
$category->delete();
session()->flash('message', 'Category Deleted');
$this->dispatchBrowserEvent('close-modal');
}
Just use the function deleteCategory with the code of destroyCategory, and let the paramenter $category_id, because deleteCategory gets the id from the view
wire:click="deleteCategory({{$category->id}})"

Laravel Livewire hide checked checkbox

in my laravel project in livewire component i need to hide/set display none or something a checked checkbox and later i need to show again if its needed . Any solutions? I could simply delete it but i wanna store it in DB
I tried do this:
https://larainfo.com/blogs/laravel-livewire-show-and-hide-div-example
but its hidding my all input checkboxes
here is my Livewire component code:
<?php
namespace App\Http\Livewire\Tasks\Types;
use App\Http\Livewire\Forms\BaseForm;
use App\Models\Task\Task;
use App\Models\Task\TaskStatus;
use App\Models\Task\TaskType;
use App\Models\Task\TaskTypeStatus;
use Livewire\Component;
use App\Traits\HasPosition;
use Mpdf\Tag\Input;
class TaskTypeStatusModal extends BaseForm
{
public $task_type_id = 0;
public $availableStatuses = [];
public $selectedStatuses = [];
public $selectedStatusesList = [];
public function mount($params = [])
{
$this->task_type_id = $params['task_type_id'];
$this->title = 'Edytuj statusy';
$this->availableStatuses = TaskStatus::orderBy('position')->get();
$this->selectedStatuses = TaskTypeStatus::where('task_type_id', $this->task_type_id)->pluck('task_status_id');
$this->selectedStatusesList = TaskTypeStatus::where('task_type_id', $this->task_type_id)->orderBy('position')->get();
}
public function submit()
{
foreach ($this->selectedStatuses as $status) {
TaskTypeStatus::create([
'task_type_id' => $this->task_type_id,
'task_status_id' => $status,
]);
}
$this->closeFromModal();
$this->emit( 'Zapisano');
$this->emit('list:refresh');
}
public function render()
{
return view('livewire.tasks.types.task-type-status-modal',[
$this->selectedStatusesList = TaskTypeStatus::where('task_type_id', $this->task_type_id)->orderBy('position')->get()
]);
}
public function reorder($list)
{
foreach ($list as $item) {
TaskTypeStatus::find($item['value'])->update(['position' => $item['order']]);
}
}
public function deleteStatus($id)
{
TaskTypeStatus::find($id)->delete();
}
and here is my blade code:
<div>
<form wire:submit.prevent="submit">
<div class="modal-header">
<h5 class="modal-title">{{ $title }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" wire:click.prevent="closeFromModal">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h6>Wybierz statusy</h6>
#forelse($availableStatuses as $availableStatus)
<div class="form-check checkbox">
<input class="form-check-input" name="status-{{ $availableStatus->id }}" id="status-{{ $availableStatus->id }}" wire:key="status-{{ $availableStatus->id }}"
wire:model.defer="selectedStatuses" type="checkbox" value="{{ $availableStatus->id }}"
wire:click="$toggle">
<label class="form-check-label" for="status-{{ $availableStatus->id }}">{{ $availableStatus->name }}</label>
</div>
#empty
<tr>
<td colspan="3">{{ __('Brak dostępnych statusów') }}</td>
</tr>
#endforelse
<hr>
<h6>Dodane statusy</h6>
<tr><span style="color:#3c4b64;font-size: 9pt"><b>{{ __('Przeciągnij za nazwę, aby zmienić kolejność.') }}</b></span></tr>
<ul class="list-group" wire:sortable="reorder">
#forelse ($selectedStatusesList as $selectedStatus)
<li class="list-group-item" value="{{ $selectedStatus->id }}" wire:sortable.item="{{ $selectedStatus->id }}" wire:key="selectedStatus-{{ $selectedStatus->id }}">
<td wire:sortable.handle>{{ __($selectedStatus->taskStatus->name) }}
<div class="float-right">
<button wire:click.prevent="deleteStatus({{ $selectedStatus->id }})" class="btn btn-sm btn-danger">{{ __('Usuń') }}</button>
</div>
</td>
</li>
#empty
<tr>
<td colspan="3">{{ __('Brak dodanych statusów') }}</td>
</tr>
#endforelse
</ul>
</div>
<div class="modal-footer">
<button wire:click.prevent="closeFromModal" class="btn btn-secondary" data-dismiss="modal">Anuluj</button>
<button type="submit" class="btn btn-primary">Zapisz</button>
</div>
</form>
</div>

Problem with Laravel CRUD (Edit Function)

Good day everyone. I'm quite new to new to Laravel and was doing some basic CRUD coding, I was able to code the add and view function, but I'm having a hard time with the edit and delete function.
I have 4 files, the master blade file, the web.php (routing), the blade file and the Form Controller.
This is the promo.blade.php file:
<table class="table table-striped" id="table1" >
<thead>
<tr>
<th class="text-center">ACTION</th>
<th class="text-center">Offer ID</th>
<th class="text-center">Promo Name</th>
<th class="text-center">Promo Price</th>
<th class="text-center">Status</th>
</tr>
</thead>
<tbody>
#foreach ($data as $key => $item)
<tr>
<td class="text-center">
<a href="#" data-bs-toggle="modal" data-bs-target="#show" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-success"><i class="bi bi-eye-fill"></i></span>
</a>
<a href="#" data-bs-toggle="modal" data-bs-target="#edit" data-mainid="{{$item->id}}" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-primary"><i class="bi bi-pencil-square"></i></span>
</a>
<a href="#" data-bs-toggle="modal" data-bs-target="#delete" data-myofferid="{{$item->offerId}}" data-mytitle="{{$item->promoName}}" data-myprice="{{$item->promoPrice}}">
<span class="badge bg-danger"><i class="bi bi-trash"></i></span>
</a>
</td>
<td class="date text-center">{{ $item->offerId }}</td>
<td class="date text-center">{{ $item->promoName }}</td>
<td class="number text-center">{{ $item->promoPrice}}</td>
<td class="number text-center">{{ $item->isActive }}</td>
</tr>
#endforeach
</tbody>
</table>
<!--Start Modal Edit -->
<div class="modal fade text-left" id="edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel160" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header bg-primary">
<h5 class="modal-title white" id="add">
Edit Promo
</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<i data-feather="x"></i>
</button>
</div>
<div class="modal-body">
<form action="{{ route('promo.edit') }}" method="POST">
#csrf
<div class="form-group">
<label for="">ID</label>
<input type="text" class="form-control" name="id" id="id" value="">
<span style="color:red">#error('id'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Offer ID</label>
<input type="text" class="form-control" name="offerId" id="offerId" value="">
<span style="color:red">#error('offerId'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Promo Name</label>
<input type="text" class="form-control" name="promoName" id="promoName" value="">
<span style="color:red">#error('promoName'){{$message}} #enderror</span>
</div>
<div class="form-group">
<label for="">Promo Price</label>
<input type="number" class="form-control" name="promoPrice" id="promoPrice" value="">
<span style="color:red">#error('promoPrice'){{$message}} #enderror</span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light-secondary" data-bs-dismiss="modal">
<i class="bx bx-x d-block d-sm-none"></i>
<span class="d-none d-sm-block">CANCEL</span>
</button>
<button type="submit" class="btn btn-primary ml-1">
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block">SAVE</span>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- End Modal Edit-->
Then this is the web.php file, for the routing:
Route::get('promo.promo', [App\Http\Controllers\FormControllerPromo::class, 'viewRecord'])->middleware('auth')->name('promo.promo');
Route::post('promo.add', [App\Http\Controllers\FormControllerPromo::class, 'addPromo'])->name('promo.add');
Route::post('promo.delete/{id}', [App\Http\Controllers\FormControllerPromo::class, 'viewDelete'])->middleware('auth');
Route::get('promo.edit', [App\Http\Controllers\FormControllerPromo::class, 'viewRecord'])->middleware('auth')->name('promo.edit');
Route::get('promo.edit/{id}', [App\Http\Controllers\FormControllerPromo::class, 'viewDetail'])->middleware('auth');
Route::post('promo.edit', [App\Http\Controllers\FormControllerPromo::class, 'edit'])->name('promo.edit');
This is the master.blade.php file:
<!--Start Modal edit for Promo-->
<script type="text/javascript">
$('#edit').on('show.bs.modal', function (event){
var button = $(event.relatedTarget)
var mainid = button.data('mainid')
var id = button.data('myofferid')
var title = button.data('mytitle')
var price = button.data('myprice')
var modal = $(this)
modal.find('.modal-body #id').val(mainid);
modal.find('.modal-body #offerId').val(id);
modal.find('.modal-body #promoName').val(title);
modal.find('.modal-body #promoPrice').val(price);
})
</script>
<!--End Modal edit for Promo-->
I think this is the part where the code wont execute properly.
This is the FormControllerPromo.php file:
// view form
public function index()
{
return view('promo.promo');
}
// view record
public function viewRecord()
{
$data = DB::table('promo')->get();
return view('promo.promo',compact('data'));
}
// view detail
public function viewDetail($id)
{
$data = DB::table('promo')->where('id',$id)->get();
return view('promo.promo',compact('data'));
}
// edit promo
public function edit(Request $request){
$id = $request->input('id');
$offerId = $request->input('offerId');
$promoName = $request->input('promoName');
$promoPrice = $request->input('promoPrice');
DB::table('promo')
->where('id', $id) // find your user by their email
->limit(1) // optional - to ensure only one record is updated.
->update(array('offerId' => $offerId, 'promoName' => $promoName, 'promoPrice' => $promoPrice)); // update the record in the DB.
$data = DB::table('promo');
return view('promo.promo',compact('data'));
}
I've been trying to code this for almost a week now with no success, any help is highly appreciated. :)
the update seems right, should work. but when you pass the $data variable to your view, you should call ->get(), because otherwise you return a query builder instance, that later raises the Undefined property error when trying to access {{$item->offerId}}.
change second last line in your example
//from this:
$data = DB::table('promo');
//to this:
$data = DB::table('promo')->get();
//or to this if you want to show only one record:
$data = DB::table('promo')->where('id', $id)->get();

I want to set local-storage and qty increment in every click when product ID already exist in cart by Vue.js

I made a shopping cart, where a product item gets added to the cart. When I click the product, it gets stored in a cart, but not local storage. I set it local-storage. When I click a product that already exists in the cart, I want to increment its quantity, but that's not happening. It adds another row instead, which I want to prevent.
Here is my component:
<template>
<div class="row">
<div class="col-md-8">
<div v-for="(product, id) in products" :key="id" class="col-xl-3 col-sm-6 mb-3 float-left">
<div class="card o-hidden h-100">
<div class="card-body">
<div class="card-body-icon">
<i class="fas fa-fw fa-comments"></i>
</div>
<div class="mr-5">{{product.name}}</div>
</div>
<div class="card-footer clearfix small z-1 form-group row" href="#">
<span class="float-left"><input type="text" v-model="product.qty" class="form-control form-control-sm mb-2"></span>
<strong class="float-right col-sm-6">
{{product.price}} TK
</strong>
<button class="btn btn-sm btn-info float-right col-sm-6" #click="addToCart(product)">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<table class="table table-sm">
<thead>
<tr>
<th>#SL</th>
<th>Name</th>
<th>Qty</th>
<th>Price</th>
<th>L/T</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(cart, i) in carts" :key="i">
<td>{{cart.id}}</td>
<td>{{cart.name}} </td>
<td class="text-right">{{cart.qty}}</td>
<td class="text-right">{{cart.price}}</td>
<td class="text-right">{{cart.price*cart.qty}}</td>
<td><button type="button" #click="removeProduct(i)" class="btn btn-sm btn-danger">x</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4" class="text-right font-weight-bold">Total</td>
<td class="text-right"> {{total}}/-</td>
</tr>
</tfoot>
</table>
<div>
<button class="btn btn-sm btn-info float-right">Checkout</button>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
products:[],
carts:[],
}
},
computed:{
total(){
var total = 0
this.carts.forEach(cart => {
total += parseFloat(cart.price * cart.qty)
})
return total
},
},
mounted(){
this.showProduct()
},
methods:{
showProduct(){
axios.get('api/pos')
.then(res=>{
this.products = res.data.data
});
},
addToCart(product){
this.carts.push(product)
},
removeProduct(i){
this.carts.splice(i,1)
}
}
}
</script>
Here is the screenshot:
The problem is addToCart() just pushes another product into the cart without checking if it already exists.
To fix the problem, update that method to find the item, and increment the item's quantity if found. Otherwise, push another item into the cart:
addToCart(product) {
if (this.carts.find(p => p.id === product.id)) {
product.qty++
} else {
this.carts.push(product)
}
}

Paginate two collections + infiniteScroll

i'm having a trouble trying to paginate a view with 2 collections, i will explain.
i am using infiniteScroll (infinite-scrollDOTcom)
i don't have code on controller that i can reutilize to show i try with arrays but for infiniteScroll only with ajax and adding a route for it, but i dont like that ideia.
im trying to do something like this (pseudocode)
data = CollectionA + CollectionB
//if i can do it, try to orderBy (but not the most important now)
data->orderBy('something')
data->paginate(x)
return view()->with('data', data)
Controller (this is only to work with the infinite scroll for now):
public function getGarantias()
{
$data = GarantiaCasa::all()->toBase()->merge(GarantiaCarro::all()->toBase())->sortBy('nome');
$data = new Paginator($data, 1, 1);
//dd($data);
return view('administrador.garantias')
->with('garantias', $data);
}
infiniteScroll:
function infiniteScroll(message) {
var loading_options = {
finishedMsg: "<div class='end-msg'>"+message+"</div>",
msgText: "<div class='center'></div>",
img: '/img/loading.gif'
};
$('#items').infinitescroll({
loading : loading_options,
navSelector : "#data .pagination",
nextSelector : "#data .pagination li.active + li a",
itemSelector : "#items tr.item"
});
}
View (the 2 foreach is only for now until new solution
<div class="col-md-10 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-body" id="data">
<div class="pull-right" onload="">
#foreach(Auth::user()->getAllSeguros() as $tiposeguro)
<div class="btn-group">
<span type="button" class="btn btn-default btn-filter" data-target="{{ $tiposeguro }}" >{{ ucfirst($tiposeguro) }}</span>
</div>
#endforeach
<div class="btn-group">
<button type="button" class="btn btn-default btn-filter" data-target="all">Todos</button>
</div>
</div>
<div class="table-container">
<table class="table table-filter">
<tbody id="items">
#foreach($garantiasCarro as $garantia)
<tr class="item" data-status="{{ $garantia->tipo }}" style="width: 500px">
<td>
<a href="#" class="pull-left">
<img src="{{ URL::to('/') }}/img/buttons/edit.png" class="media-photo">
</a>
</td>
<td>
<a href="#" class="pull-left">
<img src="{{ URL::to('/') }}/img/buttons/delete.png" class="media-photo">
</a>
</td>
<td>
<div class="media">
<div class="media-body">
<h4 class="title">
{{ $garantia->nome }}
<span class="pull-right tipo">({{ $garantia->tipo }})</span>
</h4>
<p class="summary">{{ $garantia->descricao }}</p>
</div>
</div>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<div hidden="hidden">{{ $garantias->links() }}</div>
</div>
</div>
</div>
UPDATE: now with the new Paginator i have sort of what i need but cant paginate, the infinitescroll doesnt work i think is probably because the links..
Thanks.

Resources