Laravel Livewire Edit Role Spatie - laravel

Help, I work with laravel and spatie for roles and permissions.
I want to edit my permissions
with a checkbox list
from a window Attached code:
En el componente:
public $role;
public $rol_id, $name;
public $chek = [];
public function mount(Role $role)
{
$this->role = $role;
$this->data = $role->toArray();
$this->chek = $this->role->permissions()->pluck('id')->toArray();
}
protected $rules =[
'role.name' => 'required'
];
public function render()
{
$permisos = Permission::all();
return view('roles.edit-rol-component', compact('permisos'));
}
public function update(){
$role = $this->role;
$this->validate([
'role.name' => 'required',
]);
$this->role->save();
$role->syncPermissions(['permission'=> $this->chek]);
$this->emit('alert','success','El rol se editó correctamente.');
$this->closeModalWithEvents([
RolComponent::getName() => 'renderEvent']);
}
In the view, the list generator shows me but it marks the checks wrong
#foreach($permisos as $key => $value)
<label class="inline-flex items-center">
<input wire:model.defer="chek.{{$value->id}}"
type="checkbox" value="{{ $value->id }}"
class="form-checkbox h-4 w-4 text-green-500"
#if($role->permissions->contains($value->id)) checked #endif >
<span class="ml-3 text-sm">{{ $value->name }} </span>
</label>
#endforeach

enter image description here
I am doing the edit / delete this way (as shown in the image)
Blade
<table class="table card-table table-vcenter text-nowrap table-hover table-striped datatable fs-5">
<thead>
<tr>
<th>#</th>
<th></th>
<th>Role</th>
<th></th>
<th>Permissions</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach ($roles as $id => $single)
#php
$badgeColor = ['badge bg-blue-lt',
'badge bg-azure-lt',
'badge bg-purple-lt',
'badge bg-pink-lt',
'badge bg-indigo-lt',
'badge bg-red-lt',
'badge bg-orange-lt',
'badge bg-cyan-lt',
'badge bg-yellow-lt',
'badge bg-green-lt'
];
#endphp
<tr>
<td>{{ $id + 1 }}.</td>
<td></td>
<td>{!! strtoupper($single->label) !!}</td>
<td></td>
<td>
<div class="btn-list">
#foreach ($single->permissions as $permission)
<span class="{{ $badgeColor[rand(0, 9)] }} fs-5">{{ $permission->label }} <span class="ps-1" style="cursor: pointer" wire:click='revokePermission({{ $single->id }}, {{ $permission->id }})'>x</span></span>
#endforeach
</div>
</td>
<td class="text-end">
<button class="btn btn-danger p-1 fs-6"><i class="fas fa-trash-alt"></i></button>
</td>
</tr>
#endforeach
</tbody>
</table>
Component:
public function revokePermission($roleId, $permissionId)
{
$role = Role::findOrFail($roleId);
$permission = ModelsPermission::findOrFail($permissionId);
$role->revokePermissionTo($permission->name);
$this->render();
}

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 - 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);
}

Laravel - How to disable submit when any of the title field is null

In my Laravel-5.8, I have a model called Goal:
protected $fillable = [
'id',
'weighted_score',
'title',
'start_date',
'end_date',
];
For the model, I have a controller:
Index Controller
public function index()
{
$userEmployee = Auth::user()->employee_id;
$goals = Goal::where('employee_id', $userEmployee)->get();
return view('goals.index')->with(['goals', $goals);
}
This controller renders this view
view
<div class="card-body">
<div class="table-responsive">
<table class=" table table-bordered table-striped table-hover datatable">
<thead>
<tr>
<th width="8%">
Type
</th>
<th width="11%">
Start Date - End Date
</th>
<th>
Weight(%)
</th>
<th>
</th>
</tr>
</thead>
<tbody>
#foreach($goals as $key => $goal)
<td>
{{$goal->title ?? '' }}
</td>
<td>
{{Carbon\Carbon::parse($goal->start_date)->format('M d, Y') ?? '' }} - {{Carbon\Carbon::parse($goal->end_date)->format('M d, Y') ?? '' }}
</td>
<td>
{{$goal->weighted_score ?? '' }}
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<div class="row no-print">
<div class="col-12">
<i class="fas fa-arrow-right"></i> Submit
</div>
</div>
</div>
routes:
Route::resource('goals', 'GoalsController');
Route::get('post/publish_all_posts', 'GoalsController#publish_all_posts')->name('post.publish.all');
Controller function for publish_all_posts()
public function publish_all_posts(){
$unapproved_post = Goal::where('employee_id', $userEmployee)
->update([
'is_approved' => 1
]);
}
For this that displays all the goals for this particular employee:
$goals = Goal::where('employee_id', $userEmployee)->get();
I want the application to only enable this:
<div class="col-12">
<i class="fas fa-arrow-right"></i> Submit
</div>
only when there is no NULL value in the field called title
in
$goals = Goal::where('employee_id', $userEmployee)->get();
How do I achieve this?
Thanks
You could try something like this.
#if(! $goals->pluck('title')->contains(null))
<div class="col-12">
<i class="fas fa-arrow-right"></i> Submit
</div>
#endif
when goals titles not contains null show the link using laravel collection methods. documentation
Hope it helps you.

in laravel pass updated value from view to controller without submit button

I am tiring to store manager auth id, I have view page that contents of user tickets, in my database name called "ticket" in that table I have column name called "ticket_view_by_manager_id" in this column I am trying to store manager auth id, when manager open that ticket that time manager auth id, store in this "ticket_view_by_manager_id" column,
my controller
public function manager_assigned_Chat(Request $request, $ticket_id){
$this->validate($request, [
'ticket_view_by_manager_id' => 'required',
]);
$input = User_Ticket::find($ticket_id);
$input['ticket_view_by_manager_id'] = $request->submit;
$input->save();
}
my route
Route::post('user_ticket_chat{ticket_id}', 'Services\User_TicketController#manager_assigned_Chat')->name('user_ticket_chat{ticket_id}');
my view "showing all user ticket list"
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>slNo</th>
<th>Ticket ID</th>
<th>Subject</th>
<th>Status</th>
<th>Last Update</th>
<th>Created</th>
</tr>
</thead>
<tbody>
<form method="POST" action="{{ route('user_ticket_chat{ticket_id}')}}" enctype="multipart/form-data">
#csrf
#foreach ($my_tickets as $key=>$my_tickets_list)
<tr>
<td style="text-align:center"> {{ $key + 1 }} </td>
<td >{{ $my_tickets_list->ticket_id }}</td>
<td > <input type="hidden" name="submit" value="{{ Auth::user()->staff_id }}" href="ticket_chat{{ $my_tickets_list->ticket_id }}" >{{ $my_tickets_list->subject }}</td>
<td style="text-align:center">
#if($my_tickets_list->status == 'OPEN')
<span class="btn waves-effect waves-light btn-sm btn-success">OPEN</span>
#elseif($my_tickets_list->status == 'COMPLETE')
<span class="btn waves-effect waves-light btn-sm btn-info">COMPLETE</span>
#else($my_tickets_list->status == 'PENDING')
<span class="btn waves-effect waves-light btn-sm btn-danger">PENDING</span>
#endif
</td>
<td >{{$my_tickets_list->created_at->todatestring()}} </td>
<td >{{$my_tickets_list->updated_at->todatestring()}} </td>
</tr>
#endforeach
<input type="submit" value="Send.">
</form>
</tbody>
</table>
in your web.php
Route::post('user_ticket_chat','Services\User_TicketController#manager_assigned_Chat')->name('user_ticket_chat');
in your controller
public function manager_assigned_Chat(Request $request){
$this->validate($request,[
'ticket_id' => 'required',
]);
$input = User_Ticket::find($ticket_id);
$input->ticket_view_by_manager_id = Auth::user()->id; // or Auth::user()->staff_id; in your case
$input->save();
}
in blade view add meta tag :
<meta name="csrf-token" content="{{ csrf_token() }}">
in table :
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>slNo</th>
<th>Ticket ID</th>
<th>Subject</th>
<th>Status</th>
<th>Last Update</th>
<th>Created</th>
</tr>
</thead>
<tbody>
#foreach ($my_tickets as $key=>$my_tickets_list)
<tr>
<tdstyle="text-align:center"> {{ $key + 1 }} </td>
<td>{{ $my_tickets_list->ticket_id }}</td>
<td class="ticket" data-ticketid="{{ $my_tickets_list->ticket_id}}">{{ $my_tickets_list->subject }}</td>
<td style="text-align:center">
#if($my_tickets_list->status == 'OPEN')
<span class="btn waves-effect waves-light btn-sm btn-success">OPEN</span>
#elseif($my_tickets_list->status == 'COMPLETE')
<span class="btn waves-effect waves-light btn-sm btn-info">COMPLETE</span>
#else($my_tickets_list->status == 'PENDING')
<span class="btn waves-effect waves-light btn-sm btn-danger">PENDING</span>
#endif
</td>
<td>{{$my_tickets_list->created_at->todatestring()}} </td>
<td>{{$my_tickets_list->updated_at->todatestring()}} </td>
</tr>
#endforeach
</tbody>
</table>
now using Jquery AJAX request :
<script>
$(document).on('click','.ticket',function(){
var ticketID=$(this).attr('data-ticket');
$.ajax({
url:'/user_ticket_chat',
type:'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType:'json',
data:{"ticket_id":ticketID},
success:function(response){
console.log(response);
},
error:function(){
alert('Error');
}
});
});
</script>
You should change your validator. It will be like, Please try this:
$this->validate($request, [
'submit' => 'required',
]);
Because your are not sending any info about ticket_view_by_manager_id from view.
Suggestion: may be your code is not well decorated. If you can please
have a look.

Resources