how to add value quantiy to array - laravel

I have the following code, you can go through Class Livewire and View Livewire, I got the desired result but I want to add 1 key to the half to collect, the key I want is quantity, when entering the quantity it will add to collect for me
Class Livewire
<?php
namespace App\Http\Livewire;
use App\Models\Medicine;
use App\Models\MedicineCategory;
use Livewire\Component;
class SelectMedicineCategoryTable extends Component
{
public $columns = ['STT', 'Name', 'Qty', 'Unit'];
public $medicines;
public array $selectedMedicineArray = [];
public $getAllMedicineCategory;
public $selectMedicineCategoryId = null;
public $quantity = [];
public function render()
{
$this->getAllMedicineCategory = MedicineCategory::where('status', MedicineCategory::ACTIVE)->get(['id', 'name_medicine']);
if ($this->selectMedicineCategoryId != '') {
$this->medicines = Medicine::where('status', Medicine::ACTIVE)->Where('medicine_category_id', $this->selectMedicineCategoryId)->get(['id', 'name', 'unit']);
} else {
$this->medicines = [];
}
return view('livewire.select-medicine-category-table');
}
}
View livewire
#forelse ($medicines as $item)
<tr>
<td><input class="form-check-input" type="checkbox" wire:model="selectedMedicineArray"
id="" value="{{ $item }}">
<td>{{ $loop->iteration }}</td>
</td>
<td>{{ $item->name }}</td>
<td><input type="number" wire:model="quantity.{{ $item->id }}" min="1"
id="" value="1">
</td>
<td>{{ $item->unit }}</td>
</tr>
#empty
<tr>
<td>Not found result</td>
</tr>
#endforelse
Output current
array ( 0 => '{"id":1,"name":"Padamon","unit":"V\\u0129"}', )
I want Output
array ( 0 => '{"id":1,"name":"Padamon","unit":"V\\u0129", 'quantity:...'}', )

Related

How to update when selecting select option will show checkbox in livewire

I'm having a problem I've never experienced before, I'm doing a fix function for a prescription.
I already added it but one problem when I fixed it.
I use livewire so that when I click on the drug it will show the potion by drug
Livewire Class
<?php
namespace App\Http\Livewire;
use App\Models\MedicineCategory;
use App\Models\Medicine;
use App\Models\Prescription;
use Livewire\Component;
class SelectedOldMedicineCategoryTable extends Component
{
public $columns = ['STT', 'Name', 'Quantity', 'Unit'];
public $medicines;
public $oldMedicines;
public $oldMedicineCategory;
public $prescription;
public array $selectedMedicineArray = [];
public $getAllMedicineCategory;
public $selectMedicineCategoryId = null;
public $quantity = [];
public $checkbox = false;
public function render()
{
$this->getAllMedicineCategory = MedicineCategory::where('status', MedicineCategory::ACTIVE)->get(['id', 'name_medicine']);
if ($this->selectMedicineCategoryId != '') {
$this->medicines = Medicine::where('status', Medicine::ACTIVE)->Where('medicine_category_id', $this->selectMedicineCategoryId)->get(['id', 'name', 'unit']);
} else {
$this->medicines = [];
}
return view('livewire.selected-old-medicine-category-table');
}
}
View Blade
<div>
<select name="medicine_category_id" id="" wire:model="selectMedicineCategoryId" class="form-select io-select2">
<option value="">Select Medicine Category</option>
#foreach ($getAllMedicineCategory as $row)
<option value="{{ $row->id }}"#if($prescription->medicines->containsStrict('id', $row->id)) selected="selected" #endif>
{{ $row->name_medicine }}</option>
#endforeach
</select>
#if (!empty($medicines))
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th></th>
#foreach (collect($columns) as $column)
<th>{{ $column }}</th>
#endforeach
</tr>
</thead>
<tbody>
#forelse ($medicines as $item)
<tr>
<td><input class="form-check-input" type="checkbox" name=""
wire:model="selectedMedicineArray" id="" value='{{ $item }}'>
<td>{{ $loop->iteration }}</td>
</td>
<td>{{ $item->name }}</td>
<td><input type="number" wire:model="quantity.{{ $item->id }}" id=""
min="1" value="1" class="form-control">
</td>
<td>{{ $item->unit }}</td>
</tr>
#empty
<tr>
<td>Not exists medicine</td>
</tr>
#endforelse
</tbody>
</table>
View
enter image description here
enter image description here
i want when i fix it, it will show up like that and check the checkbox for me

Returning wrong id in laravel

Departemen =
'nama_departemen',
'nama_manager',
'jumlah_pegawai',
Pegawai = 'nomor_induk_pegawai',
'nama_pegawai',
'id_departemen',
'email',
'telepon',
'gender',
'status'
PegawaiController
public function index()
{
$pegawai = Pegawai::Join('departemens','pegawais.id_departemen','=','departemens.id')->paginate(5);
return view ('pegawai.index', compact('pegawai'));
}
public function destroy($id)
{
Pegawai::find($id)->delete();
return redirect()->route('pegawai.index')->with(['success'=> 'Item Berhasil Dihapus']);
}
public function edit($id)
{
$pegawai=Pegawai::join('departemens','pegawais.id_departemen','=','departemens.id')->find($id);
$departemen = Departemen::all();
return view('pegawai.edit',compact('pegawai','departemen'));
}
pegawai.index
#forelse ($pegawai as $item)
<tr>
<td class="text-center">{{ $item->nomor_induk_pegawai }}</td>
<td class="text-center">{{ $item->nama_pegawai }}</td>
<td class="text-center">{{ $item->nama_departemen }}</td>
<td class="text-center">{{ $item->email }}</td>
<td class="text-center">{{ $item->telepon }}</td>
#if($item->gender==0)
<td>Wanita</td>
#else
<td>Pria</td>
#endif
#if($item->status==0)
<td>Inactive</td>
#else
<td>Active</td>
#endif
<td class="text-center">
<form onsubmit="return confirm('Apakah Anda Yakin ?');" action="{{ route('pegawai.destroy', $item->id ) }}" method="POST">
Edit
#csrf
#method('DELETE')
<button type="submit" class="btn btn-sm btn-danger">Hapus</button>
</form>
</td>
</tr>
#empty
<div class="alert alert-danger">
Data Pegawai belum tersedia
</div>
#endforelse
routes.web
Route::get('/', function () {
return view('dashboard');
});
Route::resource('/departemen',\App\Http\Controllers\DepartemenController::class);
Route::resource('/pegawai',\App\Http\Controllers\PegawaiController::class);
so i tried the Hapus and Edit button. it returning id_departemen instead id from table pegawai. i assume this is because im using join. i use join because i want to show nama_departemen from table departemen in pegawai. so what should i do to fix this.
maybe table departemen should look like this
'id', 'nama_departemen', 'nama_manager', 'jumlah_pegawai'
and table pegawai should look like this :
'id','nomor_induk_pegawai', 'nama_pegawai', 'id_departemen', 'email', 'telepon', 'gender', 'status'
and the controller should look like this :
Pegawai::select ('pegawai.nomor_induk_pegawai','pegawai.nama_pegawai','departemen.nama_departemen','pegawai.email','pegawai.telepon','pegawai.gender','pegawai.status','pegawai.id as id_pegawai','departemen.id as id_departemen')->Join('departemens','pegawais.id_departemen','=','departemens.id')->paginate(5);
just choose which do you want to use, id_pegawai or id_departemen
you can change the join with leftjoin if you need
read this documention for another resolved
https://laravel.com/docs/9.x/queries#select-statements
The issue here is that your are joining two tables that both have an ID column.
To get around this you need to be specific in what columns you want to return.
For example;
$pegawai = Pegawai::Join('departemens','pegawais.id_departemen','=','departemens.id')->select('pegawais.id','departemens.otherColumnName')->paginate(5);
Hope that helps.

Laravel Livewire strange table rendering behavior

I have a table component in my page that renders a list of users, and one of the columns in the table is the user's role. when I paginate through the table of users, livewire is randomly inserting a row in the table for the role, like it's somehow getting confused and including the relationship in the loop, instead of just the main model.
This is the result after paginating:
Here's what it's doing to the markup:
It only happens the first time the page is loaded and I click one of the pagination buttons. It will randomly happen on one or more pages as I paginate through the table, but once I reach the end, I can paginate through every page any number of times without seeing it again until I refresh the page.
Here is my User model:
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable, SoftDeletes, CanResetPassword, HasFactory;
protected $with = ['role'];
public function role()
{
return $this->belongsTo(Role::class);
}
}
Here's my Role model:
class Role extends Model
{
use HasFactory, SoftDeletes;
public function user()
{
return $this->hasOne(User::class);
}
}
My Livewire UserListComponent, which is a full-page component:
class UserListComponent extends Component
{
use WithPagination;
public $search;
public $roles;
public $user;
protected $paginationTheme = 'bootstrap';
protected $listeners = ['refreshUsers' => '$refresh'];
public function mount()
{
$this->search = '';
}
public function render()
{
return view('livewire.users.index', [
'users' => User::withTrashed()->search(['first_name', 'last_name'], $this->search)->paginate(5)
]);
}
public function show($id)
{
return redirect()->route('users.edit', ['user' => $id]);
}
}
My blade view:
<x-table search="true">
#slot('head')
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
#endslot
#slot('body')
#forelse($users as $user)
<x-table.row id="{{ $user->id }}" includeStatus="true" :status="$user->deleted_at">
<td>{{ $user->id }}</td>
<td>{{ $user->first_name }}</td>
<td>{{ $user->last_name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->role->name }}</td>
</x-table.row>
#empty
<x-table.empty-row colSpan="6" />
#endforelse
#endslot
#slot('paginationLinks')
{{ $users->links() }}
#endslot
</x-table>
And here's the table component content:
#props(['search' => false, 'paginationLinks' => false])
<div class="table-responsive">
<div class="d-flex flex-row justify-content-between">
<div class="col-md-3"></div>
<div class="col-md-2">
#if ($search)
<input wire:model="search" placeholder="Search" type="text" class="form-control">
#endif
</div>
</div>
<table class="table">
<thead>
<tr>
{{ $head }}
</tr>
</thead>
<tbody>
{{ $body }}
</tbody>
</table>
<div class="mt-4">
#if ($paginationLinks)
{{ $paginationLinks }}
#endif
</div>
</div>
And the table row component:
#props(['includeStatus' => false, 'status' => false, 'id'])
<tr wire:key="{{ $id }}" wire:loading.class.delay="opacity-50" wire:target="search" wire:click="show({{ $id }})">
{{ $slot }}
#if ($includeStatus)
<td>
#if ($status)
<span class=" ms-2 badge bg-danger">Inactive</span>
#else
<span class="ms-2 badge bg-success">Active</span>
#endif
</td>
#endif
</tr>

Laravel - How to Filter records using dopdown on submit

In my Laravel-5.8 project, I have this codes:
Model:
class HrEmployee extends Model
{
protected $table = 'hr_employees';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'department_id',
'first_name',
'last_name',
];
public function department()
{
return $this->belongsTo('App\Models\Hr\HrDepartment','department_id','id');
}
}
deptfilters in the controller filters the hr_employees table using department_id
Controller:
public function index(Request $request)
{
$employeedatas = HrEmployee::where('status', 1)->get();
$deptfilters = HrDepartment::where('status', 1)->pluck('department_name','id');
return view('hr.employees.index')
->with('deptfilters', $deptfilters)
->with('employeedatas', $employeedatas);
}
view
<div class="container">
<br>
<form action="ViewPages" method="POST" enctype="multipart/form-data">
#csrf
<div class="container">
<div class="row">
<label for="from" class="col-form-label">Department</label>
<div class="col-md-2">
<select id="department" name="department" class="form-control">
<option value="">--- Select department ---</option>
#foreach ($department as $key => $value)
<option value="{{ $key }}" {{ old( 'department')==$ key ? 'selected' : ''}}>{{ $value }}</option>
#endforeach
</select>
</div>
<div class="col-md-4">
<button type="submit" class="btn btn-primary btn-sm" name="search">Search</button>
</div>
</div>
</div>
</form>
<br>
<table class="table table-dark">
<tr>
<th>id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Department</th>
</tr>
#foreach ($employeedatas as $employeedata)
<tr>
<td>{{ $employeedata->id }}</td>
<td>{{ $employeedata->first_name }}</td>
<td>{{ $employeedata->last_name }}</td>
<td>{{ $employeedata->department->department_name }}</td>
</tr>
#endforeach
</table>
</div>
From the code each department has many employees. What I want to achieve is that:
By default, the dropdown should load department where current_year = 1
When the search button is submitted, I want the table to be fields with records based on the department_id in the dropdown.
How do I modify my controller and view code to achieve this?
Thanks
In general you don't need for $table and $id property when you are using Laravel conventions
class HrEmployee extends Model
{
//protected $table = 'hr_employees';//Laravel by default expect table name 'hr_employees'
//protected $primaryKey = 'id';//Laravel by default expect primary_key on table is id column
protected $fillable = [
'id',
'department_id',
'first_name',
'last_name',
];
public function department()
{
//return $this->belongsTo('App\Models\Hr\HrDepartment','department_id','id');
return $this->belongsTo('App\Models\Hr\HrDepartment');//No Need for override foreign key and owner key when you are using laravel conventions
}
}
In Controller
public function index(Request $request)
{
$employees = HrEmployee::where('status', 1);
if($request->input('department_id')){
$employees->where('department_id',$request->input('department_id'))
}
$employees=$employees->get();
$departments = HrDepartment::where('current_year',1)->where('status', 1)->pluck('department_name','id');
return view('hr.employees.index')
->with('departments', $departments)
->with('employees', $employees);
}
In View For filter use GET NOT POST METHOD
<div class="container">
<br>
<form method="get">
<div class="container">
<div class="row">
<label for="from" class="col-form-label">Department</label>
<div class="col-md-2">
<select id="department" name="department_id" class="form-control">
<option value="">--- Select department ---</option>
#foreach ($departments as $id => $name)
<option value="{{ $id }}" {{ request('depratment_id')==$id ? 'selected' : ''}}>{{ $name }}</option>
#endforeach
</select>
</div>
<div class="col-md-4">
<button type="submit" class="btn btn-primary btn-sm" name="search">Search</button>
</div>
</div>
</div>
</form>
<br>
<table class="table table-dark">
<tr>
<th>id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Department</th>
</tr>
#foreach ($employees as $employee)
<tr>
<td>{{ $employee->id }}</td>
<td>{{ $employee->first_name }}</td>
<td>{{ $employee->last_name }}</td>
<td>{{ optional($employee->department)->department_name }}</td>
</tr>
#endforeach
</table>
</div>
You have pass the data using Ajax to the controller based on your filter values you should return the results of the filter without refreshing the page
Refer this
https://www.webslesson.info/2019/07/implement-custom-search-filter-in-laravel-58-datatable-using-ajax.html?m=1
public function index(Request $request)
{
//Build initial query to fetch employee data
$employeeQuery = HrEmployee::query()->where('status', 1);
//If a department has been selected by user
//filter the employee data by the selected department_id
if(!empty($request->department)) {
$employeeQuery->where('department_id', $request->department);
}
//Get the employee data by executing the $employeeQuery
$employeedatas = $employeeQuery->get();
//Get all the departments where current_year = 1
//if current_year is not a column on the departments table
//replace where('current_year', 1) with whereYear('created_at',now()->format('Y'))
//replace 'created_at' with whichever date column you want to compare with current year
$deptfilters = HrDepartment::where('status', 1)
->where('current_year', 1)
->pluck('department_name','id');
return view('hr.employees.index')
->with('deptfilters', $deptfilters)
->with('employeedatas', $employeedatas);
}

ErrorException (E_ERROR) Undefined variable: userdata

The error message I get is:
ErrorException (E_ERROR) Undefined variable: userdata
I know these things get asked a lot. I have searched Google and here and I have already tried suggested answers to no avail.
Controller:
public function index()
{
$userdata = EditUserModel::all()->paginate(5);
return view('admin.userman')->with(['userdata' => $userdata])->with('i', (request()->input('page', 1) - 1) * 5);
}
Route:
Route::resource('admin.userman', 'EditUserController');
Model:
public class EditUserModel extends Model
{
public $table = "users";
protected $fillable = [
'id',
'name',
'email',
'role',
'password'
];
}
View:
#foreach($userdata as $data)
<tbody>
<tr>
<td>{{ $data->id }}</td>
<td>{{ $data->email }}</td>
<td>{{ $data->created_at }}</td>
<td>{{ $data->role }}</td>
<td>{{ $data->status }}</td>
<td>
Edit
</td>
<td>
#csrf
#method('DELETE')
<button class="btn btn-danger" type="submit">Delete</button>
</td>
</tr>
</tbody>
#endforeach
The output should be a table listing the contents of the users table from the database. but i'm getting undefined variable error.
You should try this:
Controller:
public function index()
{
$userdata = EditUserModel::all()->paginate(5);
$i = (request()->input('page', 1) - 1) * 5;
return view('admin.userman',compact('userdata','i'));
}
Route:
Route::resource('admin.userman', 'EditUserController');
Model:
public class EditUserModel extends Model
{
public $table = "users";
protected $fillable = [
'id',
'name',
'email',
'role',
'password'
];
}
View:
#if(isset($userdata))
#foreach($userdata as $data)
<tbody>
<tr>
<td>{{ $data->id }}</td>
<td>{{ $data->email }}</td>
<td>{{ $data->created_at }}</td>
<td>{{ $data->role }}</td>
<td>{{ $data->status }}</td>
<td>
Edit
</td>
<td>
#csrf
#method('DELETE')
<button class="btn btn-danger" type="submit">Delete</button>
</td>
</tr>
</tbody>
#endforeach
#endif
public function index()
{
$userdata = EditUserModel::all()->paginate(5);
$page = array('i'=>(request()->input('page', 1) - 1) * 5);
return view('admin.userman',compact('userdata','page'));
}

Resources