How to pass table value to the modal? - laravel

I actually have projects and modules table. When i click button,
i want to get the data from model of that specific project.
Here is my code :
this is my table where i want to show the data of modules that represent specific project.
<table class="report">
<tr>
<th class="report-th"> Module ID </th>
<th class="report-th"> Module Name </th>
<th class="report-th"> Module Status </th>
</tr>
#if($modules->where('project_id','=',$project->id))
#foreach($modules as $module)
<tr>
<td>{{$module->id}}</td>
<td>{{$module->title}}</td>
<td>{{$module->status}}</td>
</tr>
#endforeach
#endif
</table>
below is the code in controller:
public function show()
{
$sortBy = 'id';
$sortDirection = 'ASC';
if (request('sortby') || request('sortdir')) {
$sortBy = request('sortby');
$sortDirection = request('sortdir');
}
$projects = projects::orderBy($sortBy, $sortDirection)->paginate(6);
$modules= modules::all();
return view('tms.projects', compact('projects','modules'));
}

Related

How to count all the products that belongs to category(slug) Laravel 8

I am a beginner in Laravel. I need a little help.
I have an index.blade.php file which displays all the category names. When I click on on it will generate the slug link where I have all the products that in the category. So I would like to count only those products that is belongs to category's slug and display the number on the index.blade.php. Thanks for the help.
Route::get('view-category/{slug}', [ProductsController::class,'viewcategory']);
productsController:
public function viewcategory($slug){
if(Category::where('slug', $slug)->exists()){
$category = Category::where('slug', $slug)->first();
$products = Products::where('cateId', $category->id)->where('status','1')->get();
return view('admin.products.display', compact('category','products'));
}
else{
return redirect('/dashboard')->with('status',"Slug does not exist");
}
}
category Model:
class Category extends Model
{
use HasFactory;
protected $table = "categories";
protected $fullable = [
'name',
'slug',
'description',
'status',
'popular',
];
public function products(){
return $this->belongsTo(Products::class, 'id', 'cateId');
}
}
index.blade.php:
<thead>
<tr>
<th></th>
<th>Product Name</th>
<th>Category</th>
<th>Sub Category</th>
<th>Variations</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($category as $item)
<tr>
<td class="control" tabindex="0"></td>
<td>{{$item->products->productName}}</td>
<td>{{$item->name}}</td>
<td>{{$item->subCategory}}</td>
<td>{{$item->counter}}</td>
<td></td>
<td></td>
</tr>
#endforeach
</tbody>
</table>
You can still call relationships inside your blade files, so if you have a products relationship setup correctly, you only need to change your index blade to this
<td>{{$item->products()->count()</td>
If you have categories that don't have any products put this in your blade to check before showing the count (Its an if else statement just inline)
<td>{{$item->products ? $item->products()->count() : 'N/A'}}</td>
in your blade file add this line before your foreach
#if( $category->posts->count() )
//your #foreach code here
#endif

Laravel : "Object of class stdClass could not be converted to string" while pass variable into closure

I get an error like this
ErrorException
This my link index
<td>{{$cmface}}</td>
This my Routes
Route::get('/detail_face_to_face/{id}', 'FaceToFaceController#detail')->name('detail_face_to_face');
This my Controller
public function detail($id)
{
$xclass = DB::table('face_to_face')->select('Class')->where('id', $id)->first();
$tface = DB::table('tbclass')
->select('tbclass.F_Name','tbclass.Class')
->where('tbclass.Class', $xclass)
->whereNotExists(function ($query) use ($id) {
$query->select('id_user')
->from('absent')
->where([['absent.id_face_to_face', $id],['absent.type_face_to_face', '1'],])
->whereRaw('absent.id_user = tbclass.ID_No');
})
->orderBy('tbclass.F_Name', 'ASC')
->paginate(10);
return view('face_to_face.detail',['tface' => $tface]);
}
This my face_to_face.detail page
<table class="table">
<thead style="white-space:nowrap;">
<tr>
<th>No</th>
<th>Name</th>
<th>Class</th>
</tr>
</thead>
<tbody style="white-space:nowrap;">
#if($tface->count()===0)
<tr>
<td class="table-success text-center" colspan="10"><< Data is Empty >></td>
</tr>
#else
#foreach($tface as $no => $tm)
<tr>
<td>{{ ++$no + ($tface->currentPage()-1) * $tface->perPage() }}</td>
<td>{{$tm->F_Name}}</td>
<td>{{$tm->Class}}</td>
</tr>
#endforeach
#endif
</tbody>
</table>
{{ $tface->links() }}
if I click the link on the index page, i get that error
Can anyone help ???
Could you dd($xclass)?
Error is in, ->where('tbclass.Class', $xclass). You probably do ->where('tbclass.Class', $xclass->Class)
Regard

How to Generate Leave Balance Table for a particular employee using Laravel

In my Laravel-5.8 project, when an employee logs in I want to display a table as shown below that shows his Leave Balance
I have 3 tables that are applicable
class LeaveCategory extends Model
{
protected $table = 'leave_categories';
protected $fillable = [
'leave_category_name',
];
public function leavecategorydetail()
{
return $this->hasMany('App\Models\LeaveCategoryDetail');
}
}
class LeaveCategoryDetail extends Model
{
protected $table = 'leave_category_details';
protected $fillable = [
'id',
'leave_category_id',
'employment_type_id',
'no_of_days',
];
public function leavecategory()
{
return $this->belongsTo('App\Models\LeaveCategory', 'leave_category_id', 'id');
}
public function employmenttype()
{
return $this->belongsTo('App\Models\EmploymentType', 'employment_type_id', 'id' );
}
}
class LeaveRequest extends Model
{
protected $table = 'leave_requests';
protected $fillable = [
'id',
'employee_id',
'leave_category_id',
'leave_status',
'approved_days',
];
public function employee()
{
return $this->belongsTo('App\Models\Employee','employee_id');
}
public function leavetype()
{
return $this->belongsTo('App\Models\LeaveCategory','leave_category_id');
}
}
As earlier said, the expected result is to have 4 columns (Leave Category
, Applicable Leave, Approved Leave
, Available
)
Controller
public function leave_balance()
{
$userId = Auth::user()->id;
$userCompany = Auth::user()->company_id;
$employmentcategory = Employee::select('employeement_category_id')->where('employee_id', $userId)->where('is_active', 1)->first();
//Leave Category
$leavecategories = LeaveCategory::select('leave_category_name')->where('company_id', $userCompany)->get();
//Applicable Leave
$applicableleaves = DB::table('leave_categories')
->join('leave_category_details', 'leave_category_details.leave_category_id', '=', 'leave_categories.id')
->select('leave_category_details.no_of_days')
->where('leave_categories.company_id', $userCompany)
->where('leave_categories.employment_category_id',$employmentcategory)
->get();
//Approved Leave
$approvedleaves = DB::table('leave_requests')
->select('employee_id','leave_category_id', DB::raw('SUM(approved_days) AS approvedLeave'))
->where('employee_id', $userId)
->where('leave_category_id', $employmentcategory)
->where('leave_status',4)
->groupBy('employee_id', 'leave_category_id')
->get();
//Available
$availableleaves = $applicableleaves - $approvedleaves
$leavebalances = ...
return view('leave-balances')
->with('leavebalances', $leavebalances)
}
How do I combine the four queries in my controller ($leavecategories, $applicableleaves, $approvedleaves, $availableleaves) into $leavebalances and also get a view like
See the leave balance image
<thead>
<tr>
<th width="55%">
Leave Category
</th>
<th width="15%">
Applicable Leave
</th>
<th width="15%">
Approved Leave
</th>
<th width="15%">
leavebalances
</th>
</tr>
</thead>
<tbody>
<!--start foreach-->
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<!--end foreach-->
If there is no field/value for $approvedleaves, it should initialize with 0
Thank you.
bro you can try make the two querys in one like this is not perfect but you get the idea
$all = DB::table('leave_category_details')
->leftJoin('leave_categories', function($join)
{
$join->on('leave_categories.id', '=', 'leave_category_details.leave_category_id');
$join->on('leave_categories.employment_category_id',$employmentcategory);
$join->on('leave_categories.company_id','=', $userCompany);
})
->leftJoin('leave_requests', function($join)
{
$join->on('leave_requests.employee_id', '=', $userId);
$join->on('leave_requests.leave_category_id', $employmentcategory);
$join->on('leave_status',4);
})
->groupBy('leave_requests.employee_id', 'leave_requests.leave_category_id')
->select('leave_category_details.no_of_days','leave_requests.employee_id','leave_requests.leave_category_id', DB::raw('SUM(leave_requests.approved_days) AS approvedLeave'),DB::raw('SUM(leave_requests.approved_days) - leave_category_details.no_of_days AS availableleaves')
->get();
Why get each column in a separate query when you can get them all in one.
I adjusted your controller like so:
public function leave_balance()
{
$userId = Auth::user()->id;
$userCompany = Auth::user()->company_id;
$employmentCategoryId = Employee::where('employee_id', $userId)->where('is_active', 1)->value('employeement_category_id');
//Leave Table
$leaveTable = DB::table('leave_categories as lc')
->join('leave_category_details as lcd', 'lcd.leave_category_id', '=', 'lc.id')
->join('leave_requests as lr', 'lr.leave_category_id', '=', 'lc.id')
->select('lcd.no_of_days as applicableLeaves ','lc.leave_category_name as leaveCategory',DB::raw('SUM(lr.approved_days) AS approvedLeaves'))
->where([
['lc.company_id', $userCompany],
['lc.employment_category_id',$employmentCategoryId],
['lr.employee_id', $userId],
['lr.leave_status',4]
])
->groupBy('leaveCategory', 'applicableLeaves')
->get();
return view('leave-balances')
->with('leaveTable', $leaveTable)
}
$availableleaves can be calculated in the view no need to send it.
Now in your view you display them like this:
<thead>
<tr>
<th width="55%">
Leave Category
</th>
<th width="15%">
Applicable Leave
</th>
<th width="15%">
Approved Leave
</th>
<th width="15%">
leavebalances
</th>
</tr>
</thead>
<tbody>
#foreach ($leaveTable as $tableRow)
<tr>
<td>
{{$tableRow->leaveCategory}}
</td>
<td>
{{$tableRow->applicableLeaves}}
</td>
<td>
#if(!$tabelRow->approvedLeaves->isEmpty()){{$tabelRow->approvedLeaves}}#else 0 #endif
</td>
<td>
{{($tableRow->applicableLeaves - $tabelRow->approvedLeaves)}}
</td>
</tr>
#endforeach
</tbody>
HTML is not my strongest field so your table might not show as wanted but i think its all good.

Laravel and Vuejs axios delete gives no error but doesnt delete

I created a web route that must delete a contact based on a specific id and it looks like this:
Route::delete('/api/deleteContact/{id}', 'ContactController#destroy');
Then inside the controller, I have the following:
public function destroy($id)
{
// delete a contact by id
return response()->json(Contact::whereId($id), 200);
}
Inside one of my blade template files, I call the Vue component which displays the list of contacts:
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Phone</th>
</tr>
</thead>
<tbody>
<tr v-for="contact in contacts">
<td> {{ contact.id }} </td>
<td> {{ contact.name }} </td>
<td> {{ contact.phone }} </td>
<td><button class="btn btn-secondary">Edit</button></td>
<td><button #click="deleteContact(contact.id)" class="btn btn-danger">Delete</button></td>
</tr>
</tbody>
</table>
The delete button calls the deleteContact method and received the contact id in question.
The method looks like this:
deleteContact(id){
axios.delete('/api/deleteContact/' + id)
.then(res => {
for(var i = 0; i < this.contacts.length; i++) {
if(this.contacts[i].id == id) {
this.contacts.splice(i, 1);
}
}
})
.catch(err => console.log(err));
}
When I click to delete, the promise(then) occurs, however, after refreshing the page, I noticed that nothing was deleted and I see no errors in the console.
How can I successfully delete the contact based on the id passed in the deleteContact function ?
You have to append delete at the end of query like this:
public function destroy($id)
{
// delete a contact by id
return response()->json(Contact::where('id',$id)->delete(), 200);
}

laravel vue send array to backend

I want to send array of id's to backend with one button from vuejs table but i get error 500.
Logic
Check the check boxes
Collect the id's
Send id's to back-end when click on button
update the view
Code
template
<table class="table table-dark table-hover table-bordered table-striped">
<thead>
<tr>
<th class="text-center" width="50">
//the button
<button class="btn btn-outline-danger" #click="withdraw(index)">Withdraw</button>
</th>
<th class="text-center" width="50">#</th>
<th class="text-center">Amount</th>
</tr>
</thead>
<tbody>
<tr v-for="(income,index) in incomes" v-bind:key="index">
<td class="text-center">
//check box input
<input v-if="income.withdraw == '0'" type="checkbox" :id="income.id" :value="income.amount" v-model="checkedNumbers">
</td>
<td class="text-center">{{index+1}}</td>
<td class="text-center">Rp. {{formatPrice(income.amount)}}</td>
</tr>
<tr>
<td colspan="2"></td>
<td>
<span>Withdraw for today, Sum: <br> Rp. {{ formatPrice(sum) }}</span>
</td>
</tr>
</tbody>
</table>
script
export default {
data() {
return {
incomes: [],
checkedNumbers: [],
}
},
computed: {
sum() {
return this.checkedNumbers.reduce(function (a, b) {
return parseInt(a) + parseInt(b);
}, 0);
}
},
methods: {
withdraw(index) {
let checkedids = this.incomes[index]
axios.post(`/api/withdrawbutton/`+checkedids).then(response => {
this.income[index].withdraw = '1'
this.$forceUpdate()
});
}
}
}
route
Route::post('withdrawbutton/{id}', 'IncomeController#withdrawbutton');
controller
public function withdrawbutton($id)
{
$dowithdraw = Income::where('id', $id)->get();
$dowithdraw->withdraw = '1';
$dowithdraw->save();
return response()->json($dowithdraw,200);
}
Any idea where is my mistake and how to fix it?
......................................................................................................................
Don't send the list as a GET parameter, send it as a POST:
let params = {}
params.ids = this.checkedNumbers
axios.post(`/api/withdrawbutton/`, params)
.then(response => {
this.income[index].withdraw = '1'
this.$forceUpdate()
});
Controller
public function withdrawbutton(Request $request)
{
$dowithdraws = Income::whereIn('id', $request->input('ids', []));
$dowithdraws->update(['withdraw' => '1']);
return response()->json($dowithdraws->get(), 200);
}
Route
Route::post('withdrawbutton/', 'IncomeController#withdrawbutton');
And I don't think you need to update anything in the front because you already have them checked (if you want to keep them checked)

Resources