Laravel - How to Approve all the posts of a particular Employee - laravel

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

Related

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>

Button in table row redirect to another page with the data of the row in Laravel

I would like to insert a button in every row of a table and when I click on this button, it redirect me to another page with the data of the single table row using Laravel
How can I do this?
This is my form:
<html>
<table class="table">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">USERNAME</th>
<th scope="col">MAC ADDRESS</th>
</tr>
</thead>
<tbody>
#foreach ($data as $item)
<tr>
<th scope="row">{{$item->id}}</th>
<td>{{$item->username}}</td>
<td>{{$item->mac_addr}}</td>
<td>
<form action="{{url('singleDevice')}}" method="get">
<button class="btn btn-primary" type="submit">Select</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</body>
</html>
This is my controller:
class DeviceController extends Controller
{
public function index()
{
$data=Device::all();
return view('device', compact("data"));
}
public function create()
{
return view('registrationDevice');
}
public function store(Request $request)
{
$input = new Device;
//On left field name in DB and on right field name in Form/view
$input -> username = $request->username;
$input -> mac_addr = $request->mac_address;
$input->save();
return redirect('registrationDevice')->with('message', 'DATA SAVED');
}
public function show(Device $device)
{
return view('singleDevice');
}
}
Thanks in advance
Change your form like :
<tbody>
#foreach ($data as $item)
<tr>
<th scope="row">{{$item->id}}</th>
<td>{{$item->username}}</td>
<td>{{$item->mac_addr}}</td>
<td>
Select
</td>
</tr>
#endforeach
</tbody>
If you want to use route name, you can change by :
<td>
Select
</td>
Change your route like :
Route::get('/singleDevice/{deviceID}', [DeviceController::class, 'show'])->name('show');
Change your show function of the controller like:
public function show($deviceID)
{
$device = Device::firstWhere('id', $deviceID);
return view('singleDevice', compact("device"));
}
Why do you need a form? use the link
<form action="{{url('singleDevice')}}" method="get">
<button class="btn btn-primary" type="submit">Select</button>
</form>
replace with
Select
and configure the URL in the router as /singleDevice/{device}
Route::get('/singleDevice/{device}', [DeviceController::class, 'show'])->name('show');
You also can use this as you have already used form in your code
<form action="{{ route('show', $item->id) }}" method="get">
<button class="btn btn-primary" type="submit">Select</button>
</form>
public function show(Device $device)
{
return view('singleDevice');
}
For Route you can pass $device:
Route::get('/singleDevice/{$device}', [DeviceController::class, 'show'])->name('show');

I am trying to retrieve data and display it in a page in laravel 5.3

Following is my show page code to display the data:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div
class="panel-heading">subnet_behind_clients
</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="GET" action="{{ url('/subnet_behind_clients') }}">
{{ csrf_field() }}
<table class="table table-hover">
<thead>
<tr>
<th></th>
<th>client_id</th>
<th>ip_address</th>
<th>netmask</th>
</tr>
</thead>
<tbody>
#foreach($clients as $client)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $client->ip_address }}</td>
<td>{{ $client->netmask }}</td>
<td>
<button type = "button" class = "btn btn-danger " data-target = "del/{{$client->id}}">Delete</button>
</td>
/tr>
#endforeach
</tbody>
</table>
<div class="panel-body">
Home
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
and following is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Subnet_behind_client;
use DateTime;
class Subnet_Behind_ClientController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
/* $datas = Subnet_behind_client::all();
$data = $datas->first();*/
$data = Subnet_behind_client::first();
return view('subnet_behind_clients',compact('data'));
}
public function create(Request $request)
{
$data = new Subnet_behind_client;
return view('subnet_behind_clients1',compact('data'));
Subnet_behind_client::create([
//'client_id' => $request->input('1'),
'ip_address' => $request->input('ip_address'),
'netmask' => $request->input('netmask'),
]);
}
public function store(Request $request)
{
$datas = Subnet_behind_client::all();
$data = new Subnet_behind_client;
$data->client_id = '1';
$data->ip_address = $request->ip_address;
$data->netmask = $request->netmask;
$data->save();
return back();
}
public function show(Request $request)
{
$clients = Subnet_behind_client::all();
return view('view2',compact('clients'));
}
public function destroy($id)
{
$clients = Subnet_behind_client::findOrFail( $id );
$clients->delete();
return view('view2',compact('clients'));
}
}
plz let me know what is wrong for the code in foreach
the first part is the view page
and the second page is for the controller part
I made edited my earlier post. Plz take a look and let me know.
You controller should look like this:
use App\Subnet_behind_clients;
public function show(Request $request)
{
$clients = Subnet_behind_clients::all();
return view('view2', compact('clients '));
}
And view:
#foreach($clients as $client)
....
#endforeach
Never use Eloquent or Query Builder in views.
if you got Class 'App\Http\Controllers\Subnet_behind_clients' not found
use use App\Subnet_behind_clients(namespace of model) after namespace in controller
you forgot to add namespance of model in controller
try this
controller
use App\Subnet_behind_clients
public function show(Request $request)
{
$datas = Subnet_behind_clients::all();
return view('view2',compact('datas'));
}
view
#foreach($datas as $data)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $data->ip_address }}</td>
<td>{{ $data->netmask }}</td>
</tr>
#endforeach

Laravel: Undefined variable

im having a problem with my code.
I want to show the record of the student who login but im having an
undefined variable on my view.blade
Here's my Model
class Attendance extends Eloquent {
public function users()
{
return $this->belongsTo('User', 'id');
}
}
Here's my Controller
public function viewstudentAttendance()
{
$students = Auth::user()->id;
//load view and pass users
return View::make('student.view')
->with('attendances', $students);
}
Finally here's my view.blade
#extends('layouts.master')
#section('head')
#parent
<title>View Attendance</title>
#stop
{{ HTML::style('css/bootstrap.css'); }}
#section('content')
</ul>
#if ($students->count())
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
#foreach ($students as $students)
<tr>
<td>{{ $students->id }}</td>
<td>{{ $students->firstname }}</td>
<td>{{ $students->lastname }}</td>
#endforeach
</tr>
{{ HTML::script('js/bootstrap.js'); }}
</tbody>
</table>
#else
There are no attendance recorded yet
#endif
#stop
I think the problem is with my view or how i declare the variable? Please help? :(
public function viewstudentAttendance() {
//This code turns ID ONLY Check the website out for a code that retrieves data so you can loop it.
$students = Auth::user() - > id;
//Code that counts number of student
$studentCount = XXX(Google It)
//load view and pass users
return View::make('student.view') - > with('attendances', $students);
//Return StudentCount too
}
Inside your blade template, use :
#if ($studentCount > 10)
instead of
#if ($students->count())
Your students is returning ID, how could you "Count"
http://laravel.com/docs/4.2/eloquent
Inside your blade you kept doing if($students) bla bla, just to let you know it's attendances
->with('attendances', $students);
Attendances is the variable your blade will see, $student is the data you are pushing into attendances for blade

Resources