Using Livewire with multi Select2 multiple input - laravel

in one page I have to list the name of the all rooms in a loop and assign employees to the rooms. Some employees uses more than one room. I decided use Livewire for the first time. So I don't have experience with Livewire. I'm using Select2 to choose employees.
My structure is this:
Livewire View
<div>
#foreach(\App\Models\Room::all() as $room)
<div class="row">
<div class="col-2">
<div class="fw-bold">{{$room->room_code}}</div>
<div>
<p>{{$room->name}}</p>
</div>
</div>
<div class="col-8">
<div class="row">
<div class="col-10">
<select class="multiple-select" wire:model="employee.employee" data-placeholder="Choose employee" multiple="multiple">
#foreach(\App\Models\Employee::where('status', 1)->get() as $employee)
<option value="{{$employee->id}}">{{$employee->first_name." ".$employee->last_name}}</option>
#endforeach
</select>
</div>
<div class="col-1">
<button class="btn btn-danger" wire:click="assignSave({{$room->id}})"><i class="fa-solid fa-floppy-disk icon-center"></i></button>
</div>
<div class="col-1 text-success font-22">
<i class="fa-solid fa-check icon-center"></i>
</div>
</div>
</div>
</div>
#endforeach
</div>
Livewire Controller
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class RoomAssign extends Component
{
public $employee = [];
public function render()
{
return view('livewire.room-assign');
}
public function assignSave($room){
dd($this->employee);
}
}
This is the blade
#section('sub-page-content')
<h6 class="mb-0 text-uppercase">Room Assign</h6>
<hr/>
<div class="card">
<div class="card-body">
<livewire:room-assign />
</div>
</div>
#endsection
#section('customjs')
<script src="{{asset('assets/plugins/select2/js/select24.min.js')}}"></script>
<script src="{{asset('assets/js/form-select2.js')}}"></script>
<script>
$('.multiple-select').on('change', function (){
alert('asdasd');
})
</script>
#endsection
Idea is simple. Take room id and employee id and save to a pivot table both information. But I can't evet take employees array. In every loop I have a save button for that room to save records and I want to inform user is process is successful. For information I left a div to show a simple "green tick". Can you help me about taking the employee ids and notify the user?

Need to add wire:ignore for select2. I would also change the $employeevariable in your foreach since you're using it in your Livewire component as well and is more than likely causing a conflict. Use something like $employeeInfo instead for the foreach
<div class="col-10" wire:ignore>
<select class="multiple-select" wire:model="employee" id="employee" data-placeholder="Choose employee" multiple="multiple">
#foreach(\App\Models\Employee::where('status', 1)->get() as $employeeInfo)
<option value="{{$employeeInfo->id}}">{{$employeeInfo->first_name." ".$employeeInfo->last_name}}</option>
#endforeach
</select>
</div>
When using Livewire with select2 you need to setup a listener for the select
public $employee = [];
protected $listeners = [
'employee',
];
public function employee($value)
{
$this->employee = $value;
}
And in your script tag:
$(document).ready(function() {
window.initSelectDrop=()=>{
$('#employee').select2({
placeholder: '{{ __('locale.Select ....') }}',
allowClear: true});
}
initSelectDrop();
$('#employee').on('change', function (e) {
livewire.emit('employee', e.target.value)
});
});
I had this same issue, when Livewire re-renders the component it will break select2 drop downs. Using this approach select2 will act as expected.

public function storeRoomEmployees(Room $room){
$room->employees()->attach($this->employees)
}
/* some suggestions on Your code
1. instead of this #foreach(\App\Models\Room::all() as $room) in your
blade, define a variable in Livewire Controller public $rooms.
2. add mount function
public function mount(){
$this->rooms = Room::all();
}
// mount function runs before the content load
#foreach(\App\Models\Room::all() as $room) -> #foreach($rooms as $room)
*/

Related

my livewire app is returning 404 not found when I selected a dropdown item

I am designing a laravel app, which I used module and livewire. I have a dropdown item which when I selected an item its returned an error 404 NOT FOUND
Here is my livewire component.
I am thinking may the wire:model="selectedSession" and wire:model="selectedTerm" is having problem
please i need your help
<?php
namespace Modules\Student\Http\Livewire;
use Livewire\Component;
use Modules\Student\Entities\Result;
use Modules\Student\Entities\Term;
use Modules\Student\Entities\Section;
class ResultDependance extends Component
{
public $selectedSession = null;
public $selectedTerm = null;
public $results;
public function mount($id)
{
$this->results = Result::with('student', 'section', 'term', 'subject')->where('student_id', $id)->get();
}
public function render()
{
return view('student::livewire.pages.resultdependance',
['terms' => Term::all()],
['sessions' => Section::all()]
);
}
}
my blade.php codes
<div class="section">
<div class="card">
<div class="card-body">
<div class="card-title">
<h4><strong>Result</strong></h4>
<div class="form">
<form action="" method="post">
{{csrf_field()}}
<div class="form-group">
<select name="session" id="" class="form-control form-select" wire:model="selectedSession">
<option selected>Select Session</option>
#foreach($sessions as $session)
<option value="{{$session->id}}">{{$session->section_title}}</option>
#endforeach
</select>
</div>
<br>
<div class="form-group">
<select name="term" id="" class="form-control form-select" wire:model="selectedTerm">
<option selected>Select Term</option>
#foreach($terms as $term)
<option value="{{$term->id}}">{{$term->term}}</option>
#endforeach
</select>
</div>
<input type="button" value="test" wire::loading.attr='disabled'>
<h1 wire:loading>please wait</h1>
</form>
<br>
</div>
</div>
</div>
</div>
</div>
I am designing a laravel app, which I used module and livewire. I have a dropdown item which when I selected an item its returned an error 404 NOT FOUND
Here is my livewire component.
I am thinking may the wire:model="selectedSession" and wire:model="selectedTerm" is having problem
please i need your help
It's missing the logic to filter the results based on the selected session and term.
you can do it by using livewire hooks or by adding this
public function filterResults()
{
$this->results = Result::with('student', 'section', 'term', 'subject')->where('student_id', $id)->where('section_id', $this->selectedSession)->where('term_id', $this->selectedTerm)->get();
}
and in your selectedSession
<select name="session" id="" class="form-control form-select" wire:model.lazy="selectedSession" wire:change="filterResults">
Now when the user changes the selected session or term, the component will filter the results and update the view accordingly.

Livewire magic actions not working Uncaught ReferenceError: $event is not defined

<div class="row">
<div class="col">
<div class="container">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col">
<div class="mb-5">
<label class="form-label">Order: </label>
<select wire:change="selectOrder($event.target.value)">
#foreach($orders as $option)
<option value="{{$option['id']}}">{{$option['id']}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
public function selectOrder($order)
{
$this->order = $order;
$this->products = $this->order->products;
}
here is a live wire component that has a select input I need when changing the select the function selectOrder is executed with the selected value, i use $event magic action but i got the following error.
The $event is the Alpine.js magic property.
So one way to solve it is to have use an Alpine.js event listener, that calls the Livewire method.
<select x-on:change="$wire.selectOrder($event.target.value)">
That said, you could use a property in the Livewire class, and bind the select to a model,
<select wire:model="orderValue">
And then in the component listen for that change.
public $orderValue;
// ...
public function updated($field, $value)
{
if ($field === 'orderValue') {
$this->selectOrder($value);
}
}

select2 on Laravel Livewire does not work

I implemente select2 in a select as the official documentation indicates and I can't get it to work in full.
<div>
<div wire:ignore>
<select class="js-example-basic-single" name="state">
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
</select>
<!-- Select2 will insert it's DOM here. -->
</div>
#push('scripts')
<script>
$(document).ready(function() {
$('.js-example-basic-single').select2();
$('.js-example-basic-single').on('change', function (e) {
#this.set('foo', e.target.value);
});
});
</script>
#endpush
if I remove the following script in the view the select2 component renders fine
$('.js-example-basic-single').on('change', function (e) {
#this.set('foo', e.target.value);
});
but of course I lose the desired functionality.
The selct2 add links I use are as follows
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="{{asset('SitioWeb/assets/select2/js/select2.min.js')}}"></script>
what am i missing?
Due to the way select2 works, livewire's wire:model and wire:change may not work with select2. Livewire's wire:model and wire:change work perfectly with the traditional HTML select control. To use select to with livewire's wire:model and wire:change, write a js code to get the selected value from select2, then use Livewire.emit() to send the selected value to your component and handle it from there. Example js code is as follows:
$(document).ready(function() {
$('#id').select2();
$('#id').on('change', function(e) {
Livewire.emit('listenerReferenceHere',
$('#id').select2("val"));
});
});
Your Livewire component :
...
protected $listeners = ['listenerReferenceHere'];
public function listenerReferenceHere($selectedValue)
{
//Do something with the selected2's selected value here
}
I hope this helps... 😊
you can use Bootstrap-select
npm install bootstrap-select
It worked well for me. this my code.
<div class="form-group">
<label for="permissions">{{ __('role.permissions') }}</label>
<div class="col-sm-10">
<div wire:key="UNIQUE_KEY">
<div wire:ignore>
<select id="permissions" wire:model="permissions"
data-live-search="true"
data-actions-box="true"
title="{{__('generic.select')}} {{ __('role.permissions') }}"
name="permissions[]" data-width="100%"
class="selectpicker permissions" multiple>
#foreach($list_permission as $permission)
<option value="{{ $permission->id }}"
data-subtext="{{ $permission->key }} {{ ' -'. $permission->table_name }}">
{{ __('permission.'.$permission->key) }}
</option>
#endforeach
</select>
</div>
</div>
#error('permissions') <span class="text-danger">{{ $message }}</span> #enderror
</div>
</div>
in script :
....
#push('scripts')
<script>
Livewire.restart();
$(function () {
$('.permissions').selectpicker();
});
</script>
#endpush
</div>
in Component
public $permissions = [];
public $old_permissions = [];
public function updatedPermissions()
{
$filter_arrays = array_filter($this->permissions);
$unique = array_unique($filter_arrays);
$this->permissions = $unique;
}
in update :
if (! empty($this->old_permissions)){
$updateRole = $this->role->find($this->modelId)->permissions()->detach();
$updateRole = $this->role->find($this->modelId)->permissions()->sync($validatedData['permissions']);
}elseif ($this->old_permissions != $this->permissions ){
$updateRole = $this->role->find($this->modelId)->permissions()->attach($validatedData['permissions']);
}
I tried hard to combine livewire with select2 and finally found the solution that way.
UsersComponent.php
class Users extends Component
{
public $users = [];
public function mount()
{
$this->users= User::all();
}
public function render()
{
return view('livewire.users');
}
}
then
users.blade.php
<div class="col-sm-12 col-xl-3 m-b-30" wire:ignore >
<div >
<h4 class="sub-title" >USERS</h4>
<select class="js-example-basic-single form-control-warning" name="states" >
#foreach ($users as $user)
<option value="{{ $user->id }}">{{ $user->name}}</option>
#endforeach
</select>
</div>
</div>
index.blade.php
<p>
#livewire(livewire.users)
</p>

Array to string conversion using laravel

I am trying to send a multi user-id into the database when I select users from the checkbox then I click to submit so I face error Array to string conversion how can I resolve this issue? please help me thanks.
please see error
https://flareapp.io/share/17DKWRPv
controller
public function adduseraction(REQUEST $request)
{
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$user=Users_permissions::create([
'user_id'=>$useradd,
'user_Access_id'=> $checkid
]);
$user->save();
}
html view
<div class="card card-success">
<div class="card-header">
<h3 class="card-title">Users Permission </h3>
</div>
<br>
<form action="{{route('adduseraction')}}" method="post">
{{ csrf_field() }}
<div class="col-sm-4">
<select name="userid" class="form-control">
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->name}}</option>
#endforeach
</select>
</div>
<div class="card-body">
<!-- Minimal style -->
<div class="row">
#foreach($users as $user)
<div class="col-sm-2">
<div class="form-check">
<input type="checkbox" name="multiusersid[]" value="{{$user->id}}" class="form-check-input" >
<h5 style="position:relative;left:10px;">{{$user->name}}</h5>
</div>
<!-- checkbox -->
</div>
#endforeach
</div>
<!-- /.card-body -->
</div>
<div class="card-footer">
<button type="submit" name="btnsubmit" class="btn btn-primary col-md-2
center">Submit</button>
</div>
</form>
</div>
<!-- /.content-wrapper -->
Route
Route::post('adduseraction','AdminController#adduseraction')->name('adduseraction');
** current status **
{"_token":"4Z3ISznqKFXTMcpBKK5tUgemteqxuJjQpKF8F0Ma","userid":"6","multiusersid":["2","5","7"],"btnsubmit":null}
use implode($checkid, ',');
public function adduseraction(REQUEST $request)
{
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$user=Users_permissions::create([
'user_id'=>$useradd,
'user_Access_id'=> implode($checkid, ',');
]);
}
Change in your Users_permissions model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Users_permissions extends Model
{
protected $table = 'userspermissions';
protected $fillable = [
'user_id','user_Access_id'
];
}
Here is your solution
public function adduseraction(REQUEST $request)
{
$useradd=$request->get('userid');
$checkid=implode(",", $request->get('multiusersid'));
Users_permissions::create([
'user_id'=>$useradd,
'user_Access_id'=> $checkid
]);
}
It is expecting a string and you are passing an array of ids. You may want to change the database to json or do json_ecode(checkid). Which will stringify your array. then you can store. However, remember you will need to convert it back with typecasting or manually doing it.
example:
public function adduseraction(REQUEST $request)
{
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$user=Users_permissions::create([
'user_id'=>$useradd,
'user_Access_id'=> json_encode($checkid)
]);
// $user->save(); // yes obviously not needed
}

How to stay data on dropdown list after page reloading in laravel 5.7?

I am creating task like dependent dropdown but i want to stay data as it is after reloading of page. I am successful to achieve this task for first dropdown but i am confuse how can i stay data for second dropdown Plz need help. I am putting value in session and check in option value but i am confuse in second option value that how can i check session value in javascript option value.
Blade :
<?php $reason_id=Session::get('reason_id');?>
<div class="row">
<div class="col-lg-4">
<span><label><b>Reason for return</b></label></span>
</div>
<div class="col-lg-8 mt-1">
<div class="form-group">
<select class="form-control" id="reason" name="reason">
<option readonly>Select reason</option>
#foreach($reason as $id => $p_reason)
<option value="{{ $id }}" #if($reason_id==$id) selected="selected"#endif>{{$p_reason}}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-4">
<span><label><b>Reason Details</b></label></span>
</div>
<div class="col-lg-8 mt-1">
<div class="form-group">
<select class="form-control" id="reason_detail" name="reason_detail">
</select>
</div>
</div>
</div>
javascript:
$(document).ready(function(){
$('#reason').change(function(){
var ID = $(this).val();
if(ID){
$.ajax({
type:"GET",
url:"{{url('get-reason-details')}}?reason_id="+ID,
success:function(res){
if(res){
$("#reason_detail").empty();
$("#reason_detail").append('<option>Select Reason Detail</option>');
$.each(res,function(key,value){
$("#reason_detail").append('<option value="'+key+'">'+value+'</option>');
});
}else{
$("#reason_detail").empty();
}
}
});
}else{
$("#reason_detail").empty();
}
});
controller:
public function set_session(Request $req)
{
$data=$req->all();
Session::put('reason_id',$data['reason']);
Session::put('reason_detail_id',$data['reason_detail']);
$data=DB::table('product_details')->select('product_details.*')->where('product_id',$data['product_id'])->first();
$reason=DB::table('reason')->pluck('description','reason_id');
return view('returnproduct',['reason'=>$reason],['data'=>$data->product_id]);
}
public function get_reason($id)
{
$data=DB::table('product_details')->select('product_details.*')->where('product_id',$id)->first();
$reason=DB::table('reason')->pluck('description','reason_id');
return view('returnproduct',['reason'=>$reason],['data'=>$data->product_id]);
}
public function get_reason_details(Request $req)
{
$reason_detail_id=Session::get('reason_detail_id');
$reason_details = DB::table("reason_details")
->where("reason_id",$req->reason_id)
->pluck("reason_detail","reason_detail_id");
return response()->json($reason_details);
}

Resources