How to check if checkbox is checked for each row - laravel-5

If one row is checked if($isset->has('test')) returns all rows.
I only want to save the marked rows.
My view file:
<tbody>
#foreach($match->homeTeam->players as $player)
<tr>
<th scope="row">{{$player->id}}</th>
<td class = "col-md-6" name = "player[]" value = "{{$player->id}}">{{$player->name}} {{$player->surname}}</td>
<td align="center" class= "col-md-2"><input class="form-check-input" type="checkbox" name="test" value="{{$player->id}}"></td>
<td class = "col-md-2"><input name="minutes[]" class="form-control"></td>
<td class = "col-md-2"><input name="goals[]" class="form-control"></td>
</tr>
#endforeach
</tbody>
Controller:
public function storeMatchFacts(Match $match, Request $request, Match_fact $match_fact, Player $player)
{
$home_team_players=$match->homeTeam->players;
if($isset->has('test')) {
foreach ( $home_team_players as $k => $p ) {
$data[] = [
'match_id' => $match->id,
'player_id' => $player->id,
'minutes' => $request['minutes'][$k],
'goals' => $request['goals'][$k]
];
}
dd($data);
} else {
dd('error');
}

Related

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

Laravel5.1, Relation, EloquentORM, Many to Many, Sort

<table border="true">
<tr>
<th style="width:100px">Table</th>
<th colspan="3" style="width:300px">Columns</th>
</tr>
<tr>
<td style="width:100px">Articles</td>
<td style="width:100px">id</td>
<td colspan="2" style="width:200px; color: #aaaaaa">other dependent variables</td>
</tr>
<tr>
<td style="width:100px">Article_Tag</td>
<td style="width:100px">id</td>
<td style="width:100px">article_id</td>
<td style="width:100px">tag_id</td>
</tr>
<tr>
<td style="width:100px">Tags</td>
<td style="width:100px">id</td>
<td style="width:100px">name</td>
<td style="width:100px"></td>
</tr>
</table>
Then, I want to sort Articles table by [name] of Tags table.
I tried eager-loading with closure below, but it did'nt work.
Model Article and Tag are connected with each other just by belongsToMany,
and I succeed in output their data, but they weren't sorted.Offcourse, I did'nt give getTag any argument.(When I gave argument, they weren't narrowed by [name] either.)
use App\Article;
use App\Tag;
...
public function __construct(Article $article)
{
$this->article = $article;
}
...
public function getTag($tag = NULL)
{
$flag = isset($tag);
$articles = $this->article->orderBy('created_at', 'desc')->with([
'tags' => function($query) use ($flag, $tag){
($flag)
? $query->where('name', $tag)
: $query->orderBy('name');
}
])->paginate(15);
Try this variant:
$articles = $this->article->with([
'tags' => function($query) use ($flag, $tag){
return $flag
? $query->where("name", $tag);
: $query->orderBy("name")
}
])->paginate(15);

How to insert many forms in db using Datatables

I tried to submit many forms with datatables. User has to choose the number ot input rows, in which he can submit some information - it's something like Phpmyadmin when you insert rows in db. Names of the input rows are the same. I use loop to show many rows. But in this way with nested foreach, when I submit info in two rows, in database there are 8 rows. How to do that?
Here's my view:
echo form_open('admin/add_questions/');
?>
<table id='example'>
<thead>
<tr><th>Question</th><th>Code</th><th>Group</th><th>Is_reverse</th></tr>
</thead>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
<tbody>
<?php for($i=0; $i<=20; $i++) {
?>
<tr>
<td>
<input type="text" name="question[]" id="add_question_table" />
</td><td>
<input type="text" name="code[]" id="add_question_table" />
</td><td>
<input type="text" name="group[]" id="add_question_table" />
</td><td>
<input type="text" name="is_reverse[]" id="add_question_table" />
</td></tr>
<?php
}
?>
</tbody>
</table>
My Model is:
<?php
class Admin_model extends CI_model {
public function __construct() {
parent:: __construct();
$this->load->database();
$this->load->library('session');
}
public function add_questions() {
$date = new DateTime("now");
foreach($this->input->post('question') as $v) {
foreach($this->input->post('code') as $f) {
foreach($this->input->post('group') as $val) {
$data = array(
'question'=>$v ,
'code'=>$f,
'survey_id'=>$this->uri->segment(3),
'group_id'=>$val,
'created_at'=>$date->format('Y-m-d H:i:s')
);
$this->db->insert('survey_questions',$data);
}
}
}
What's the way to do it? :)
Hi from my perspective its best to pass $_POST as a parameter to your add_questions() model method. You may try the following approach :)
//controller code
$this->admin_model->add_questions($_POST);
//model code
function add_questions($data=array())
{
if(count($data) > 0)
{
$date = new DateTime("now");
for($i=0;$i<count($data['question']);$i++){
$insert = array();
$insert['question'] = $data['question'][$i];
$insert['code'] = $data['code'][$i];
$insert['survey_id'] = $data['survey_id'][$i];
$insert['group_id'] = $data['group_id'][$i];
$insert['created_at'] = $date->format('Y-m-d H:i:s');
$this->db->insert('survey_questions',$insert);
}
}
}

Laravel Excel - blank sheets when creating multiple sheets

I had this working, using Laravel 4 and Laravel Excel to export data from mySQL. I have objects for Regtype and Attendee and I want one sheet per regtype with all related attendees. I had a single sheet of attendees exporting great. Now I've added a loop for the regtypes and I'm able to get multiple sheets but all sheets are blank!
Perhaps I have to use shareView? I wouldn't think so.. I get no errors and none of the data I pass to the blade template is displaying.
My export function:
public function export()
{
$date = date('Y_m_d');
\Excel::create('CMO_Connect_Attendees_Export_'.$date, function($excel) {
$regtypes = Regtype::all();
foreach ($regtypes as $regtype) {
if( $regtype->attendees(3)->count() ) {
$excel->sheet($regtype->name, array('regtype' => $regtype), function($sheet) {
$date = date('Y_m_d');
$attendees = new Attendee;
$atts = Attendee::where('block_id', '=', \Input::get('block_id'))
->where('regtype_id', '=', $regtype->id)
->get();
$sheet->setStyle(array(
'font' => array(
'name' => 'Arial',
'size' => 12,
'bold' => false
)
));
$sheet->loadView('attendees.export', array('atts' => $atts))->with('curdate',$date)->with('regtype_name',$regtype->name);
$atts = '';
});
} //endif
} //endforeach
$excel->export('xls');
});
}
And the blade template I'm passing data to (I pass the attendees and also the date and name of the regtype to display at the top of the sheet:
<html>
<table>
<tr>
<td colspan="11">Attendees Export - {{ $curdate }} - {{ $regtype_name }}</td>
</tr>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Company</td>
<td>Title</td>
<td>Email</td>
<td>Phone</td>
<td>Address</td>
<td>Addres 2</td>
<td>City</td>
<td>State</td>
<td>Zip</td>
<td>Date Created</td>
</tr>
#foreach($atts as $att)
<tr>
<td> {{ $att->firstname }} </td>
<td> {{ $att->lastname }} </td>
<td> {{ $att->company }} </td>
<td> {{ $att->title }} </td>
<td> {{ $att->email }} </td>
<td> {{ $att->phone }} </td>
<td> {{ $att->address }} </td>
<td> {{ $att->address2 }} </td>
<td> {{ $att->city }} </td>
<td> {{ $att->state }} </td>
<td> {{ $att->zip }} </td>
<td> {{ $att->created_at }} </td>
</tr>
#endforeach
</table>
</html>
Thanks for any help!
I sorted out - below is my export function now. I updated the vendor files through composer (realized I was on a slightly older version) and revised my code with use($regtype when calling the $sheet method (passing the regtype object into the sheet). I assumed that you'd pass variables or objects into the sheet the same way you pass data into the blade template but that's not correct.
public function export()
{
$date = date('Y_m_d');
\Excel::create('CMO_Connect_Attendees_Export_'.$date, function($excel) {
$excel->setTitle('CMO Connect Attendee Data Export');
$excel->setCreator('Dylan Glockler')
->setCompany('Bryan Allen Events');
$excel->setDescription('All attendee event data for Adobe CMO Connect');
$regtypes = Regtype::all();
$summary = '';
foreach ($regtypes as $regtype) {
if( $regtype->attendees(3)->count() ) {
$summary = $summary . $regtype->name;
$summary = $summary . ': '.$regtype->attendees(3)->count();
$summary = $summary . ' | ' . $regtype->id . '<br />';
$excel->sheet($regtype->name, function($sheet) use($regtype) {
$date = date('Y_m_d');
$atts = Attendee::where('block_id', '=', \Input::get('block_id'))
->where('regtype_id', '=', $regtype->id)
->get();
$sheet->setStyle(array(
'font' => array(
'name' => 'Arial',
'size' => 12,
'bold' => false
)
));
$sheet->loadView('attendees.export')->with('curdate',$date)->with('atts',$atts)->with('regtype_name',$regtype->name)->with('att_count',$regtype->attendees(3)->count());
});
} //endif
} //endforeach
$excel->export('xls');
});
}

Resources