Laravel Livewire Select Search Dropdown not working - laravel

I have a form in the Laravel Livewire project and try to search and select users from the database. When I search User then search results in users, but nothing to select. Also, no error showing just page refresh. my code is below:
I'm trying this
livewire component view
<div class="col-md-4">
<div class="form-group row">
<label class="control-label col-md-2 col-sm-2">Select User</label>
<div class="col-md-10 col-sm-10 ">
<div>
<select wire:model="user_id" class="form-control" name="user_id" required>
<option></option>
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->username}} : {{ $user->fullname }}</option>
#endforeach
</select>
</div>
<div style="position:relative">
<input wire:model.debounce.500ms="inputsearchuser" class="form-control relative" type="text"
placeholder="search..."/>
</div>
<div style="position:absolute; z-index:100">
#if(strlen($inputsearchuser)>2)
#if(count($searchusers)>0)
<ul class="list-group">
#foreach($searchusers as $searchuser)
<li class="list-group-item list-group-item-action">
<spanwire:click
="selectuser({{$searchuser->id}},{{$searchuser->terms}})">{{$searchuser->username}}
: {{$searchuser->fullname}}</span>
</li>
</ul>
#endforeach
#else
<li class="list-group-item">User Not Found...</li>
#endif
#endif
</div>
</div>
</div>
</div>
livewire component
class MyLiveWireComponent extends Component
{
public $j = 1;
public $users = [];
public $inputsearchuser = '';
public $user_id;
public function selectuser($user_id,$terms)
{
$this->user_id = $user_id;
$this->terms = $terms;
$this->inputsearchuser = '';
}
public function render()
{
$searchusers = [];
if (strlen($this->inputsearchuser) >= 2) {
$searchusers = User::Where('username', 'LIKE', '%' . $this->inputsearchuser . '%')
->get();
}
return view('livewire.admin.orders.add-order', ['searchusers' => $searchusers])->layout('components.layouts.admin');
}
}

Change this:
<spanwire:click="selectuser({{$searchuser->id}},{{$searchuser->terms}})">
{{$searchuser->username}} : {{$searchuser->fullname}}
</span>
To:
<span wire:click.prevent="selectuser({{$searchuser->id}},{{$searchuser->terms}})">
{{$searchuser->username}} : {{$searchuser->fullname}}
</span>

Your component should have a single-level root element only. Also, add wire:key in your element inside of the loop.
<ul class="list-group">
#foreach($searchusers as $key => $searchuser)
<li wire:key="{{'users'.$key}}" class="list-group-item list-group-item-action">
<span wire:click="selectuser({{$searchuser->id}},
{{$searchuser->terms}})">{{$searchuser->username}}
: {{$searchuser->fullname}}</span>
</li>
#endforeach
</ul>

Did you change it to wire:click.prevent as suggested above? Otherwise, it does not prevent the default action from occurring, and can cause that exact behavior.

Related

Pre-Populating Parent Child Form from DB

I have tried prepopulating the forms from DB records, not happening for child form, I have use all conventions for Laravel table, pivot table etc., still nothing. The array display with the dd('$allTariffs') but doesn't show on view file, please help am stuck with
ErrorException
foreach() argument must be of type array|object, null given
Edit Component Code
<?php
namespace App\Http\Livewire\Admin;
use App\Models\Products;
use App\Models\Tariffs;
use Livewire\Component;
class AdminEditTariffsComponent extends Component
{
// public $productId;
public $tariffId;
public $allTariffs = [];
public $rowProducts = [];
public $tariffName;
public function mount ($tariffId)
{
$this->rowProducts = Products::all();
$tariff = Tariffs::where('id', $tariffId)->first();
$this->tariffName = $tariff->tariff_name;
// $allTariffs = $tariff->products()->where('tariffs_id', $tariffId)->get()->toArray();
$allTariffs = $tariff->products->find($tariffId);
// var_dump($allTariffs) ;
// dd( $allTariffs);
foreach ($allTariffs->products as $product)
{
['productId' => $product->pivot->products_id, 'basicCharge' => $product->pivot->basic_charge, 'additionalCharge' => $product->pivot->additional_charge];
}
}
public function updateStatus()
{
$tariff = Tariffs::find($this->tariffId);
$tariff->tariff_name = $this->tariffName;
$tariff->created_by = auth()->user()->id;
$tariff->save();
foreach ($this->allTariffs as $product) {
$tariff->products()->sync($product['productId'],
['basic_charge' => $product['basicCharge'],
'additional_charge' => $product['additionalCharge']]);
}
session()->flash('message', 'Tariff added successfully!');
return redirect('/admin/tariffs/');
}
public function addProduct()
{
$this->allTariffs[] = ['productId' => '', 'basicCharge' => '', 'additionalCharge' => ''];
}
public function removeProduct($index)
{
unset($this->allTariffs[$index]);
$this->allTariffs = array_values($this->allTariffs);
}
public function render()
{
$rowProducts = Products::all();
return view('livewire.admin.admin-edit-tariffs-component',['rowProducts'=>$rowProducts])->layout('layouts.admin.base');
}
}
Edit View
<div class="container-fluid">
<!-- Begin Page Content -->
<!-- Page Heading -->
<div class="row">
<div class="col-lg-8">
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Edit Tariff</h6>
</div>
<div class="card-body">
<form wire:submit.prevent="editTariff">
#csrf
<div class="form-row">
<!-- Default input -->
<div class="form-group col-md-8">
<input type="text" class="form-control" placeholder="Enter Tariff Name"
wire:model="tariffName" required>
</div>
</div>
<hr>
<div class="card">
<div class="card-header">
<h6 class="text-primary">Products, Basic and Weight Charges</h6>
</div>
<div class="card-body">
<table class="table" id="products_table">
<thead>
<tr>
<th>Product</th>
<th>Basic Charge</th>
<th>Weight Charge</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach ($allTariffs as $index => $allTariff)
<tr wire:key="tariff-{{ $value->wireKey }}">
<td>
<select
wire:model="allTariffs.{{$index}}.productId"
class="custom-select custom-select-sm form-control form-control-sm">
<option value="">Select Product</option>
#foreach ($rowProducts as $product)
<option value="{{ $product->id }}">
{{ $product->product_name }}
</option>
#endforeach
</select>
</td>
<td>
<input type="text"
class="form-control custom-select-sm form-control form-control-sm"
placeholder="Basic Charge"
wire:model="allTariffs.{{$index}}.basicCharge" required>
</td>
<td>
<input type="text"
class="form-control custom-select-sm form-control form-control-sm"
placeholder="Weight Charge"
wire:model="allTariffs.{{$index}}.additionalCharge" required>
</td>
<td>
<a href="#" wire:click.prevent="removeProduct({{$index}})" class="btn btn-danger btn-circle btn-sm">
<i class="fas fa-trash"></i>
</a>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="row">
<div class="col-md-12">
<a href="#" wire:click.prevent="addProduct" class="btn btn-success btn-circle btn-sm">
<i class="fas fa-plus"></i>
</a>
</div>
</div>
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-3">
<button type="submit" class="form-control btn btn-small btn-primary">Edit
Tariff</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
Model File
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tariffs extends Model
{
use HasFactory;
protected $table = "tariffs";
public function products()
{
return $this->belongsToMany(Products::class, 'products_tariffs',
'products_id', 'tariffs_id')
->withPivot('basic_charge', 'additional_charge');
}
public function productstariffs()
{
return $this->hasMany(ProductsTariffs::class);
}
}
I have tried prepopulating the forms from DB records, not happening for child form, I have use all conventions for Laravel table, pivot table etc., still nothing. The array display with the dd('$allTariffs') but doesn't show on view file, please help am stuck with
ErrorException
foreach() argument must be of type array|object, null given .thankyou
In your foreach in your mount function, you are creating an array but you aren't assigning it to anywhere. Therefore, $allTariffs is empty.
Also, you're casting your variables by default as an array. You are setting $rowProducts as a Collection, however. But then in your render you are also getting the $rowProducts again. I'd suggest removing the = [] and removing the fetching of the $rowProducts each render.
public $allTariffs = [];
public $rowProducts;
public $tariffName;
public function mount ($tariffId)
{
$this->rowProducts = Products::all();
// This assumes the $tarrifId always exists. If this isn't the case, perhaps
// wrap the related code in an "if ($tariff instanceof Tariff)"
$tariff = Tariffs::find($tariffId);
$this->tariffName = $tariff->tariff_name;
foreach ($tariff->products as $product) {
$this->allTariffs[] = ['productId' => $product->id, 'basicCharge' => $product->pivot->basic_charge, 'additionalCharge' => $product->pivot->additional_charge];
}
}
public function render()
{
return view('livewire.admin.admin-edit-tariffs-component')->layout('layouts.admin.base');
}

select2 not showing options within livewire component

I am working with laravel livewire.There is a component to update brands and categories of a product. category and brand select option is a select2 option. dropdown showing as a select2, but does not show the options.
This is my component
<?php
namespace App\Http\Livewire\Components\MemberArea\Product;
use App\Models\ProductBrand;
use App\Models\ProductCategory;
use App\Models\Product;
use Illuminate\Support\Facades\Session;
use Livewire\Component;
class UpdateProductBrand extends Component
{
public $product_id;
public $product_category_id;
public $product_brand_id, $categories, $brands, $product;
public function render()
{
return view('pages.products.components.update-product-brand');
}
public function mount()
{
$this->product = Product::get($this->product_id);
$this->categories = ProductCategory::all();
$this->brands = ProductBrand::all();
$this->product_category_id = $this->product->product_category_id;
}
public function submit()
{
$data = $this->validate();
$product = Product::get($this->product_id);
Product::update($product, $data);
session()->flash('message', 'Brand Details Updated Successfully.');
}
}
This is My Blade
<div class="card-body">
<form wire:submit.prevent="submit">
<div class="row">
<div class="form-group col-lg-6">
<label class="h5">Product Category <sup class="text-danger">*</sup>|<button type="button"
id="new-category" class="btn btn-light ">+</button></label>
<select required class="form-control" wire:model="product_category_id" id="categories_edit">
<option value=""></option>
#foreach ($categories as $category)
<option {{ $product->product_category_id === $category->id ? 'selected' :'' }}
value="{{ $category->id }}">{{
$category->title }}</option>
#endforeach
</select>
</div>
#error('product_brand_id')
<span class="text-danger error">{{ $message }}</span>
#enderror
<div class="form-group col-lg-6">
<label class="h5">Product Brand <sup class="text-danger">*</sup>| <button type="button" id="new-brand"
class="btn btn-light">+</button></label>
<select class="form-control" wire:model="product_brand_id" id="brands_edit">
#foreach ($brands as $brand)
<option {{ $product->product_brand_id === $brand->id ? 'selected' :'' }} value="{{ $brand->id }}">
{{ $brand->title }}
</option>
#endforeach
</select>
</div>
#error('product_category_id')
<span class="text-danger error">{{ $message }}</span>
#enderror
<div class="form-group col-lg-12 text-center">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</form>
</div>
#push('js')
<script>
document.addEventListener("livewire:load", function (event) {
window.livewire.hook('afterDomUpdate', () => {
$('#categories_edit, #brands_edit').select2({
placeholder: 'Select an option',
});
});
});
$(document).ready(function () {
$('#categories_edit').select2();
$('#brands_edit').select2();
});
//set category on select
$('#categories_edit').on('change', function (e) {
var category_select = $('#categories_edit').select2("val");
console.log("category when select= " + category_select);
#this.product_category_id = category_select;
});
//set brand on select
$('#brands_edit').on('change', function (e) {
var brand_select = $('#brands_edit').select2("val");
console.log("brand when select= " + brand_select);
#this.product_brand_id = brand_select;
});
</script>
#endpush
this is how show it
when use wire:ignore it also not working. show only dropdown as select2 , but it does not show the options

LaravelShoppingcart package, rowId property not working

Hi I'm using the LaravelShoppingcart package(https://github.com/bumbummen99/LaravelShoppingcart) and When I output {{ $item->rowId }} on the blade template I get the rowId on the browser when the blade is rendered but when I pass it in the qtyIncreased({{ $item->rowId}}) method and try to dump and die it in the livewire component it doesn't work. Mark you when I pass the $item->id and dump and die it, it works. The only error I'm getting is on the console and is:
Error handling response: TypeError: Cannot destructure property 'yt' of 'undefined' as it is undefined.
at chrome-extension://cmedhionkhpnakcndndgjdbohmhepckk/scripts/contentscript.js:535:6
Any assistance is highly appreciated.
Live wire blade component
<div class="cart-overlay {{ $active ? 'transparent' : '' }}">
<div class="cart {{ $active ? 'showCart' : '' }}">
<span class="close-cart" wire:click="$emit('closeCart')">
<i class="fas fa-window-close"></i>
</span>
<h2>Cart</h2>
<div class="cart-content">
#foreach ($cartContent as $item)
<div class="cart-item">
<img src="{{ $item->options->image }}" alt="product" />
<div>
<h4>{{ $item->name }}</h4>
<h5>${{ $item->price }}.99</h5>
<span class="remove-item">remove</span>
</div>
<div>
<i class="fas fa-chevron-up" wire:click="qtyIncreased({{ $item-
>rowId }})"></i>
<p class="item-amount">{{ $item->qty }}</p>
<i class="fas fa-chevron-down"></i>
</div>
</div>
#endforeach
</div>
<div class="cart-footer">
<h3>your total : $ <span class="cart-total">{{ $cartTotal }}</span></h3>
<button class="clear-cart banner-btn">clear cart</button>
</div>
</div>
</div>
Livewire Class component
<?php
namespace App\Http\Livewire;
use Gloudemans\Shoppingcart\Facades\Cart;
use Livewire\Component;
class CartOverlay extends Component
{
public $active = false;
public function render()
{
$cartContent = Cart::content();
$cartTotal = Cart::total();
return view('livewire.cart-overlay', compact(['cartContent', 'cartTotal']));
}
public $listeners = [
'showCart',
'closeCart'
];
public function qtyIncreased($rowId)
{
dd($rowId);
}
public function showCart()
{
$this->active = true;
}
public function closeCart()
{
$this->active = false;
}
}
I managed to fixed it, the parameter in the function should be passed in as a string. So, I added quotes around the parameter. Changed it from <i class="fas fa-chevron-up" wire:click="qtyIncreased({{ $item->rowId }})"></i>
TO
<i class="fas fa-chevron-up" wire:click="qtyIncreased('{{ $item->rowId }}')"></i>

Laravel search from multi select dropdown

I am trying to create a search filter using dropdown selections. The code only shows results when all dropdowns (make and model) are selected. But it should work even single dropdown (either make or model)is selected. At the moment, if I select a single dropdown, the result page shows "No Matching Data found". this is what I have done -
Controller
class CarFrontController extends Controller
{
public function index_classiccars(Request $request)
{
$filterMakes = DB::table('cars')->select('make')->distinct()->get()->pluck('make');
$filterModels = DB::table('cars')->select('model')->distinct()->get()->pluck('model');
$classiccar = Car::query();
if ($request->has('make')) {
$classiccar->where('make', $request->make);
}
if ($request->has('model')) {
$classiccar->where('model', $request->model);
}
return view(
'layouts.frontend.cars.classiccars_index',
[
'filterMakes' => $filterMakes, 'filterModels' => $filterModels,
'classiccars' => $classiccar->get()
]
);
}
public function store(Request $request)
{
return $request->all();
return view('layouts.frontend.cars.classiccars_index');
}
}
data blade
#forelse ($classiccars as $car)
<div class="row">
<div class="col-lg-5 col-md-5 col-pad">
<div class="car-thumbnail">
<a href="car-details.html" class="car-img">
<div class="price-box">
<span>£{{ $car->price }}</span>
</div>
#php $i=1; #endphp
#foreach ($car->join_caralbum as $image)
#if ($i>0)
<img class="d-block w-100" src="{{asset($image->image_location)}}" alt="car" height="225px" >
#endif
#php $i--; #endphp
#endforeach
</a>
<div class="carbox-overlap-wrapper">
<div class="overlap-box">
<div class="overlap-btns-area">
<a class="overlap-btn" href="{{ url('car_show/'.$car->id) }}">
<i class="fa fa-eye-slash"></i>
</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-7 col-md-7 col-pad align-self-center">
<div class="detail">
<h3 class="title">
{{ $car->make }}
</h3>
<ul class="custom-list">
<li>
{{ $car->model }} /
</li>
......
</ul>
<ul class="facilities-list clearfix">
.....
.....
....
</ul>
</div>
</div>
</div>
</div>
#empty
No matching data found
#endforelse
filter blade
{!! Form::open(['action'=>'CarFrontController#index_classiccars','method'=>'GET']) !!}
<select class="form-control" name="make" id="make">
<option> Make(All)</option>
#foreach ($filterMakes as $make)
<option value="{{ $make }}">{{ $make }}</option>
#endforeach
</select><br>
<select class="form-control" name="model" id="model">
<option> Model(All)</option>
#foreach ($filterModels as $model)
<option value="{{ $model }}">{{ $model }}</option>
#endforeach
</select><br>
{{ Form::submit('Update Search',['class'=>'btn btn-primary']) }}
Your query results empty because even if you don't select any of your options, you actually do. If options don't have a value, the value is the text you give it to the option.
In your case, if you select just a model, actually you are selected 'Make(All)' option too. You can see this simply by putting dd($request->all()) on your index_classiccars method.
For checking selects, you can give empty value to first(default) option and control it with request()->filled('input').

How do I change the route depending on selection in laravel

I'm trying to create a page that lets the user select a product and then when they press "add to cart" that product then gets sent to the cart page.
On my product page I can have the same item that has 2 or more codes attached to it, so I've created a selection that has the codes and the user then has to pick one of them
and then press "add to cart" button to go to the cart page.
So the way I have it at the moment is that the form grabs the id of the product page and not of the selection box.
What I would like to know is how would I go about changing the route depending on what I've selected.
Here is my code
<form action="{{ route('product.addToCart', ['id' => $product->id]) }}" method="POST">
{{ csrf_field() }}
<div class="row">
<div class="col-lg-12 pl-0">
<select class="form-control mb-2" id="supplier_code" name="supplier_code">
#foreach($parent_product as $parent)
<option value="{{ $parent->supplier_code }}">{{ $parent->supplier_code }}</option>
#if(count($parent->parent))
#foreach($parent->parent as $child)
<option value="{{ $child->supplier_code }}">{{ $child->supplier_code }}</option>
#endforeach
#endif
#endforeach
</select>
</div>
</div>
{{ Form::submit('Add to Cart', array('class' => "btn btn-dark btn-lg btn-block")) }}
</form>
This is my function
public function getAddToCart(Request $request, $id)
{
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$contacts = Contact::all();
$product = Product::find($id);
$supplier_code = $request->supplier_code;
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($product, $product->id, $supplier_code);
$request->session()->put('cart', $cart);
return view('public.shopping-cart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice, 'menus_child' => $menus_child, 'contacts' => $contacts, 'supplier_code' => $supplier_code]);
}
This is my product list page where the user will click on a product to get its details.
<div class="col-xl-9 col-lg-8 col-md-12 product-list">
<div id="parent">
<div class="row grid-container">
#foreach($products as $product)
<?php
$cat_slug = "";
?>
#foreach($product->category as $category)
<?php
$cat_slug .= " ".$category->slug
?>
#endforeach
<?php
$product_image = getImagesArray($product->image);
?>
<div class="product_items col-xl-2 col-lg-4 col-md-4 col-sm-4 {{ $cat_slug }}">
<a href="{!! route('product.item', [$product->slug]) !!}">
<div>
#if(!empty($product_image))
<img src={!! "product_images/products/$product_image[0]" !!}>
#endif
<p>
{!! $product->title !!}
</p>
</div>
</a>
</div>
#endforeach
</div>
</div>
</div>
I'm not sure if I need to add anything else, so if I do need to please let me know
Change this:
<a href="{!! route('product.item', [$product->slug]) !!}">
to this:
<a href="{{ route('product.item', $product->id) }}">

Resources