Returning wrong id in laravel - 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.

Related

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 CRUD search function

I need your help that how can i make a search function for my laravel crud system?
I would like to make a search function where admins can search about users name and it works like a filter and after the search only shown the users that equals with the search.
admin.users.index (Blade file):
<div class="col-md-4">
<form action="/search" method="GET">
<div class="input-group">
<input type="search" name="search" class="form-control">
<span class="input-group-btn">
<button type="submit" class="btn btn-primary">Keresés</button>
</span>
</div>
</form>
</div>
<div class="card">
<table class="table">
<thead>
<tr>
<th scope="col">Profilkép</th>
<th scope="col">Név</th>
<th scope="col">Email</th>
<th scope="col">Telefonszám</th>
<th scope="col">Műveletek</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<th scope="row"><img src="/uploads/avatars/{{ $user->avatar }}" style=" width:32x; height:32px; float:left; border-radius:50%; margin-right:25px;"></th>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->phone }}</td>
<td>
<a class="btn btn-sm btn-primary" href=" {{ route('admin.users.edit', $user->id) }}" role="button">Szerkesztés</a>
<button type="button" class="btn btn-sm btn-danger" onclick="event.preventDefault(); document.getElementById('delete-user-form-{{ $user->id }}').submit()">
Törlés
</button>
<form id="delete-user-form-{{ $user->id }}" action="{{ route('admin.users.destroy', $user->id) }}" method="POST" style="display: none;">
#csrf
#method("DELETE")
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
{{ $users->links() }}
</div>
UserController Search function:
public function index(Request $request)
{
if(Gate::denies('logged-in')){
dd('no acces');
}
if(Gate::allows('is-admin')){
return view('admin.users.index', ['users' => User::paginate(10)]);
}
dd("adminnak kell lenned");
$users = User::paginate(10);
return view('admin.users.index')
->with([
'users' => $users
]);
}
public function search(Request $request) {
$search = $request->get('search');
$users = User::table('users')->where('name', 'like', '%'.$search.'%')->paginate(10);
return view('admin', ['users' => $users]);
}
And i dont have route in web.php because i dont know how can i solve this. :(
Please help me!
thank you for your reply!
$('.table').DataTable({
"paging": true,
"pageLength": 10,
"scrollY": 850,
"scrollX": true,
"columnDefs": [{
"targets": -1,
"orderable": false,
},
],
"ordering": false,
});
Put this command to javascript.
add this css
https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css
add this js
https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js
this is datatable search without anything. if you want use this method.

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 Approve all the posts of a particular Employee

Using Laravel-5.8, I have written a code for post of employees and it is working perfectly:
Controller
public function index()
{
$userEmployee = Auth::user()->employee_id;
$posts = Post::latest()->where('employee_id', $userEmployee)->get();
return view('admin.post.index', compact('posts'));
}
And it generates this view shown below. The view loads all the unapproved posts for a particular employee:
<table class="table table-bordered table-striped table-hover dataTable js-exportable">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th><i class="material-icons">visibility</i></th>
<th>Is Approved</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($posts as $key=>$post)
<tr>
<td>{{ $key + 1 }}</td>
<td>{{ str_limit($post->title,'10') }}</td>
<td>{{ $post->user->name }}</td>
<td>{{ $post->view_count }}</td>
<td>
#if($post->is_approved == true)
<span class="badge bg-blue">Approved</span>
#else
<span class="badge bg-pink">Pending</span>
#endif
</td>
<td>
#if($post->status == true)
<span class="badge bg-blue">Published</span>
#else
<span class="badge bg-pink">Pending</span>
#endif
</td>
</tr>
#endforeach
</tbody>
<form action="{{route('admin.post.approve', $post->id)}}" method="POST" enctype="multipart/form-data">
#csrf
#method('PUT')
<div>
<button type="submit" class="btn btn-primary"><i class="fas fa-arrow-right"></i> {{ trans('global.submit') }}</button>
</div>
</form>
I want to add a submit button to the view called approve. Once the button is clicked, it checks where is_approved is = 0 for the loaded employee and turns all the is_approved that relates to the employee (the loaded) data to 1.
I have written this function in the same controller, but I see that it will only work for a selected row:
public function approve($id){
$post = Post::find($id);
if ($post->is_approved == false){
$post->is_approved = true;
$post->save();
$post->user->notify(new AuthorPostApprove($post));
Toastr::success('Post Successfully Approved');
}else{
Toastr::info('Post is already Approved');
}
return redirect()->back();
}
and have this route/web.php
Route::get('posts/', 'PostController#index')->name('post.index');
Route::put('/post/{id}/approve', 'PostController#approve')->name('post.approve');
How do I re-write my Controller, view and route to achieve this?
Thank you.
try this:
public function approve($id){
$post = Post::where('employee_id', $id)
->where('is_approved', 0)
->update(['is_approved' => 1]);
if ($post){
$post->user->notify(new AuthorPostApprove($post));
Toastr::success('Post Successfully Approved');
} else {
Toastr::info('Post is already Approved');
}
return redirect()->back();
}
Ok I do something like below
All you need to do is that when user click the button then it should call for a function where that function will update all unapproved posts. So Im implementing it as below.
First I load all the unapproved post of the current logged in user . With just adding extra where clause in to your index function
Controoler for all unapproved posts
public function index()
{ //Fetching all unapproved post and passing it into view
$userEmployee = Auth::user()->employee_id;
$posts = Post::latest()->where('employee_id', $userEmployee)->where('is_approved',0)->get();
return view('admin.post.index', compact('posts'));
}
Defining the route
Define a route like below first and that route will call for the function named as approve_all_posts in PostController .
Route::post('/post/approve_all_posts', 'PostController#approve_all_posts')->name('post.approve.all');
New function for update
Then I make the function approve_all_posts () in PostController
public function approve_all_posts(){
$unapproved_post = Post::where('is_approved',0)->update(['is_approved' => 1]);
return redirect()->back();
}
Update blade file with button
Then in admin/post/index.blade.php
I add a button called approve all posts like below
Approve all unapproved posts

Unable to collect data from my PostController using Laravel

I am trying to create a feature on my web application that allows the user to see the posts between two dates. However, I am having problems trying to pass data from my database to my blade template. Instead of retrieving the created_at date of the post I receive the date "1/01/1970" and the job number does not appear.
First I added the routes in my web.php file:
Route::get('/search', function () {
return view('search');
});
Route::post('/select', 'PostController#getDate');
In my PostController.php file, I added my getDate Function:
public function getDate(Request $request){
$posts = DB::table('jobs')
->whereBetween('created_at', [$request->fdate, $request->sdate])
->get();
$posts->created_at = $request->created_at;
$posts->job_number = $request->job_number;
return view('result', ['posts' => $posts]);
}
My search.blade.php which is the form:
<form method="POST" action="/select">
{{ csrf_field() }}
<div class="form-group">
<label>First Date:</label>
<input type="date" class="form-control" name="fdate">
</div>
<div class="form-group">
<label>Second Date:</label>
<input type="date" class="form-control" name="sdate">
</div>
<input type="submit" value="Get Post Between" class="btn btn-primary">
</form>
My result.blade.php file which shows the post.
#if(count( $posts )>0)
<table class="table table-bordered table-striped">
<thead>
<th>Date created</th>
<th>Job Number</th>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{ date('j/m/Y', strtotime($posts->created_at)) }}</td>
<td>{{ $posts->job_number }}</td>
</tr>
#endforeach
</tbody>
</table>
#else
<h3 class="text-center">No Post from Selected Range</h3>
#endif
I am honestly confused, I have used the correct variables.
Here you are appending properties to a collection object not to each element
$posts->created_at = $request->created_at;
$posts->job_number = $request->job_number;
to add these properties to each element you should use map() or loop the elements.
foreach($posts as $post) {
$post->created_at = $request->created_at;
$post->job_number = $request->job_number;
}
you should use the single post not the whole array to get the date
change
<td>{{ date('j/m/Y', strtotime($posts->created_at)) }}</td>
with
<td>{{ date('j/m/Y', strtotime($post->created_at)) }}</td>
same stuff for the {{ $posts->job_number }} -> {{ $post->job_number }}

Resources