I want to add pagination in my custom laravel query.
Here is my code.
$jobseekers = Jobseeker::where('employer_id', Auth::employer()->get()->id)->get()->toArray();
$jobs = Job::select('id')->where('employer_id', (Auth::employer()->get()->id))->get()->toArray();
$apps = DB::table('applications')
->leftJoin('jobseekers', 'applications.jobseeker_id', '=', 'jobseekers.id')
->groupby('jobseekers.id')
->whereIn('applications.job_id', $jobs)
->get();
$apps_array = array();
for ($i = 0; $i < count($apps); $i++) {
$apps_array[$i] = (array) $apps[$i];
}
$jobseeker = array_merge($jobseekers, $apps_array);
return view('frontend.manageCV', compact('jobseeker', 'assignJS'));
Try this and let see how it goes
// I have changed the get to paginate
$jobseekers = Jobseeker::where('employer_id', Auth::employer()->get()->id)->paginate();
$jobs = Job::select('id')->where('employer_id', (Auth::employer()->get()->id))->get()->toArray();
$apps = DB::table('applications')
->leftJoin('jobseekers', 'applications.jobseeker_id', '=', 'jobseekers.id')
->groupby('jobseekers.id')
->whereIn('applications.job_id', $jobs)
->get();
$apps_array = array();
for ($i = 0; $i < count($apps); $i++) {
$apps_array[$i] = (array) $apps[$i];
}
// I am merging to the $jobseekers->data in $jobseekers array
$jobseekers->data = (object)array_merge((array)$jobseekers->data, $apps_array);
return view('frontend.manageCV', compact('jobseekers', 'assignJS'));
Related
i hope you are all doing ok.
I have a weird problem that i just can't find a way to solve and the worst part I don't even know how to start looking for this problem over the internet.
Here's the case:
I make a DB request with the code below in Laravel:
public function previsao(){
$dados = [];
$tempoEntrega = 0;
$tempoTroca = 0;
$sugestaoCompra = 0;
$frequencia = 0;
$qnt = 0;
$qntI = 0;
$qntR = 0;
$todosOsDados = $this->TecManutencaoEstoquePecaRegM
->join('tec_manutencao_pecas', 'tec_manutencao_estoque_peca_regs.pecaId', 'tec_manutencao_pecas.id')
->where('dataComp', '!=', null)
->get();
foreach ($todosOsDados as $todId) {
$toIds[] = $todId->pecaId;
}
$idsUnicos = array_unique($toIds);
foreach ($idsUnicos as $idu) {
$ids[] = $idu;
}
foreach ($ids as $id) {
$peca = $this->TecManutencaoPecasM
->select('peca')
->where('id', $id)
->first();
$entrega = $this->TecManutencaoEstoquePecaRegM
->join('tec_manutencao_pecas', 'tec_manutencao_estoque_peca_regs.pecaId', 'tec_manutencao_pecas.id')
->where('dataComp', '!=', null)
->where('pecaId', $id)
->where('mov', 'i')
->select('data', 'dataComp', 'qnt', 'est_min')
->get();
foreach ($entrega as $e) {
$tempoEntrega += (Carbon::parse($e->data)->diffInDays(Carbon::parse($e->dataComp)));
$estMin = $e->est_min;
$qntI += $e->qnt;
}
$qntRetirada = $this->TecManutencaoEstoquePecaRegM
->join('tec_manutencao_pecas', 'tec_manutencao_estoque_peca_regs.pecaId', 'tec_manutencao_pecas.id')
->where('dataComp', '!=', null)
->where('pecaId', $id)
->where('mov', 'r')
->select('qnt')
->get();
foreach ($qntRetirada as $qr) {
$qntR += $qr->qnt;
}
$qnt = $qntI - $qntR;
$uso = $this->TecManutencaoEstoquePecaRegM
->where('pecaId', $id)
->where('mov', 'r')
->select('data')
->get();
foreach ($uso as $u) {
$ultimaEntrega = $this->TecManutencaoEstoquePecaRegM
->join('tec_manutencao_pecas', 'tec_manutencao_estoque_peca_regs.pecaId', 'tec_manutencao_pecas.id')
->where('pecaId', $id)
->where('mov', 'i')
->where('data', '<=', $u->data)
->select('data')
->orderBy('data', 'DESC')
->first();
$tempoTroca += (Carbon::parse($u->data)->diffInDays(Carbon::parse($ultimaEntrega->data)));
$ultimaTroca = $u->data;
}
$frequencia = count($entrega);
$sugestaoCompra = round(($tempoTroca * ($tempoEntrega + $frequencia)) - ($qnt - $estMin));
$tempoTrocaMedio = count($uso) == 0 ? $tempoTroca : round($tempoTroca / count($uso));
$tempoAteEstminAcabar = $qnt * $tempoTrocaMedio;
$dataProxComp = $tempoAteEstminAcabar - round($tempoEntrega / count($entrega));
$diasTroca = $tempoTroca <= 0 ? round($tempoEntrega / count($entrega)) : $dataProxComp;
$dados[] = [
'id' => $id,
'peca' => $peca->peca,
'tempoEntrega' => $tempoEntrega <= 0 ? $tempoEntrega : round($tempoEntrega / count($entrega)),
'tempoTroca' => $tempoTroca <= 0 ? $tempoTroca : round($tempoTroca / count($uso)),
'qntProxComp' => $sugestaoCompra,
//'dataProxComp' => date('d/m/Y', strtotime($ultimaTroca.'+'.$diasTroca.' days')),
'dataProxComp' => $ultimaTroca == 0 || $ultimaTroca == null ?
date('d/m/Y', strtotime($ultimaEntrega->data.'+'.$diasTroca.' days')) :
date('d/m/Y', strtotime($ultimaTroca.'+'.$diasTroca.' days')),
'qnt' => $qnt,
'estMin' => $estMin
];
$tempoEntrega = 0;
$tempoTroca = 0;
$sugestaoCompra = 0;
$frequencia = 0;
$qnt = 0;
$qntI = 0;
$qntR = 0;
}
//dd($dados);
return $dados;
}
This code returns what I've expected:
Then a get this return with Vue like this:
methods: {
getPredictions(){
axios.get(this.rotagetprevisoes, this.dadosIniciais).then(res => {
this.dadosIniciais = res.data
console.log(res.data)
})
},
rowClass(filtered, type){
if (!filtered) return
if (filtered.estMin < filtered.qnt) return 'table-success'
if (filtered.estMin = filtered.qnt) return 'table-warning'
if (filtered.estMin > filtered.qnt) return 'table-danger'
},
openRepModal(){
this.$root.$emit('bv::show::modal', 'gerRelPrev', '#btnShow')
},
sugModal(item){
if(item.qntProxComp >= 0){
this.qntSuges = item.qntProxComp
this.acimaEstMin = 'n'
} else {
this.qntSuges = Math.abs(item.qntProxComp)
this.acimaEstMin = 's'
}
this.dataSuges = item.dataProxComp
this.$root.$emit('bv::show::modal', 'adminSugestao', '#btnShow')
}
},
But what I got here is:
Note that the "estMin" has different values when is sent and when is received, the weirdest part is that it only goes from Laravel to Vue, nothing in the middle.
I already try changing a lot of parts of my code, doing it all over again but, ended up with the same result, try searching for something related over the internet but no succeed.
This field "estMin" is the only one affected and, it's not even a calculated field, it's only the data that I get from DB.
I simply don't understand why "estMin" comes from Laravel with the values that I expect and arrive in Vue with a different value.
One more thing, this is an array of objects, only pick one example to show you guys.
Can someone help me please?
thanks for trying to help me, i just figure what I was doing wrong and, it was stupid.
I've edited the question so you guys can have a better understand:
In the rowClass method, I have this line:
if (filtered.estMin = filtered.qnt) return 'table-warning'
I didn't notice the '=' sign, that's why the estMin was aways with a different value so, I change the '=' sign for '===' and the problems were solved:
if (filtered.estMin === filtered.qnt) return 'table-warning'
Honestly, I don't understand why exactly this method can be interfering with the other but, it is working.
Again, thank you all that have tried to help me.
I am building a pharmacy management system. I have a condition where I need to build a section
As shown in the picture, I need to store the data where the upper three should be same for all of the rows inputted below.
The form data is submitted as in the below picture.
But the data when looped and saved is not being saved as desired. Only the last row of the data is being inserted and I am also confused to store supplier, purchase date and note since these data should be repeated as many as the number of rows are added.
PurchaseController.php
public function storePurchase(PurchaseStoreRequest $request)
{
$purchase = new Purchase();
$count = count($request->name);
// return response()->json($request->all());
for ($i = 0; $i < $count; $i++) {
$purchase->supplier = $request->supplier;
$purchase->purchase_date = $request->purchase_date;
$purchase->description = $request->description;
$purchase->category = $request->category[$i];
$purchase->name = $request->name[$i];
$purchase->generic_name = $request->generic_name[$i];
$purchase->batch_number = $request->batch_number[$i];
$purchase->company = $request->company[$i];
$purchase->strength = $request->strength[$i];
$purchase->expiry_date = $request->expiry_date[$i];
$purchase->quantity = $request->quantity[$i];
$purchase->selling_price = $request->selling_price[$i];
$purchase->purchase_price = $request->purchase_price[$i];
$purchase->save();
}
return response()->json(['message' => 'Purchase Saved Successfully']);
}
Can someone help me to store these three fields in the database repeating the number of rows submitted ?
Currently only the last row is being inserted into the database.
This might be an another way to accomplish what you're looking for.
$sharedKeys = ['supplier', 'purchase_date', 'description'];
$sharedData = $request->only($sharedKeys);
$multiKeys = ['category', 'name', 'generic_name', 'batch_number', 'company', 'strength', 'expiry_date', 'quantity', 'selling_price', 'purchase_price'];
$multiData = $request->only($multiKeys);
for ($i = 0; $i < count($request->name); $i++) {
$individualData = array_combine($multiKeys, array_column($multiData, $i));
Purchase::create($sharedData + $individualData);
}
For every loop, you need to create a new instance, then It will create a new record on each loop :
public function storePurchase(PurchaseStoreRequest $request)
{
// $purchase = new Purchase();
$count = count($request->name);
// return response()->json($request->all());
for ($i = 0; $i < $count; $i++) {
$purchase = new Purchase(); // create new instance end with (); on each loop
$purchase->supplier = $request->supplier;
$purchase->purchase_date = $request->purchase_date;
$purchase->description = $request->description;
$purchase->category = $request->category[$i];
$purchase->name = $request->name[$i];
$purchase->generic_name = $request->generic_name[$i];
$purchase->batch_number = $request->batch_number[$i];
$purchase->company = $request->company[$i];
$purchase->strength = $request->strength[$i];
$purchase->expiry_date = $request->expiry_date[$i];
$purchase->quantity = $request->quantity[$i];
$purchase->selling_price = $request->selling_price[$i];
$purchase->purchase_price = $request->purchase_price[$i];
$purchase->save();
}
return response()->json(['message' => 'Purchase Saved Successfully']);
}
on my array push i want to concat the 2 data if they have the same date
$goal = Goal::where('employee_id',Auth::user()->employees->first()->id)
->with('accomplishments')->orderBy('date','asc')->get();
$next_week = $goal->whereBetween('date',[$add_start_date,$add_end_date]);
$last_week = $goal->whereBetween('date',[$sub_start_date,$sub_end_date]);
$goals = [];
$date = "";
for ($i=0; $i < count($next_week); $i++) {
if($next_week[$i]['date']==$date){
$goals[$i-1]['activity'] = $goals[$i-1]['activity'] .', '. $next_week[$i]['activity'];
continue;
}
array_push($goals,$next_week[$i]);
$date = $next_week[$i]['date'];
}
when using filtering on laravel collections, indexes are lost,
to re_index the result array, use 'values':
$next_week = $goal->whereBetween('date',[$add_start_date,$add_end_date])->values();
$last_week = $goal->whereBetween('date',[$sub_start_date,$sub_end_date])->values();
I'm trying to addDays to a date using Carbon with Laravel, but I don't get why I'm receiving this error. I have checked some posts in StackOverflow, but no one has helped me to solve it.
This is my code:
$user = Auth::user();
$orders = DB::table('orders')->where('user_id', Auth::user()->id)->get();
$totalValue = 0;
$percentage = 0;
$currentDate = $carbon->now();
$currentDate = Carbon::parse($currentDate)->format('d/m/Y');
//$percentage = ($order->price * 0.05) / 30;
foreach($orders as $order) {
$nextDate = Carbon::parse($order->created_at)->format('d/m/Y');
if(1 == 1) {
$nextDate->addDays(1);
DB::table('orders')->where('user_id', Auth::user()->id)->update(['profit' => $order->profit]);
}
The error:
Try to add a day before change date format like below.
Carbon::parse($currentDate)->addDays(1);
or
Carbon::parse($currentDate)->addDay();
The simple way to add a day from today date is Carbon::now()->addDay();
Thanks.
I guess you are not saving your created_at date properly. Try following code.
$user = Auth::user();
$orders = DB::table('orders')->where('user_id', Auth::user()->id)->get();
$totalValue = 0;
$percentage = 0;
$currentDate = $carbon->now();
$currentDate = Carbon::parse($currentDate)->format('d/m/Y');
//$percentage = ($order->price * 0.05) / 30;
foreach($orders as $order) {
$nextDate = \Carbon\Carbon::parse($orders[0]->created_at)->format('d/m/Y');
$new_date = \Carbon\Carbon::createFromFormat('d/m/Y',$nextDate)->addDays(1)->toDateString();
if(1 == 1) {
//$nextDate->addDays(1);
$new_next_date = date('d/m/Y',strtotime($new_date));
DB::table('orders')->where('user_id', Auth::user()->id)->update(['profit' => $order->profit]);
}
I am using Joomla! K2 v2.4.1 component on Joomla! v1.5.23. I want to display latest items by category in the item view page, the category being the current one which the current viewed item belongs to.
There are modules which I can use to display most recent items by category but I want to modify item.php and other related files (actually I don't know which files to edit except the item.php template file) to accommodate this requirement. Is it possible to achieve this? If yes, which files do I need to edit and with what code?
Given below is what I think is used to retrieve latest items by category.
class K2ViewLatest extends JView {
function display($tpl = null) {
$mainframe = &JFactory::getApplication();
$params = &JComponentHelper::getParams('com_k2');
$user = &JFactory::getUser();
$cache = &JFactory::getCache('com_k2_extended');
$limit = $params->get('latestItemsLimit',3);
$limitstart = JRequest::getInt('limitstart');
$model = &$this->getModel('itemlist');
$itemModel = &$this->getModel('item');
if($params->get('source')){
$categoryIDs = $params->get('categoryIDs');
if(is_string($categoryIDs) && !empty($categoryIDs)){
$categoryIDs = array();
$categoryIDs[]=$params->get('categoryIDs');
}
$categories = array();
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'tables');
if(is_array($categoryIDs)){
foreach($categoryIDs as $categoryID){
$category = & JTable::getInstance('K2Category', 'Table');
$category->load($categoryID);
if ($category->published && ($category->access <= $user->get('aid', 0))) {
//Merge params
$cparams = new JParameter($category->params);
if ($cparams->get('inheritFrom')) {
$masterCategory = &JTable::getInstance('K2Category', 'Table');
$masterCategory->load($cparams->get('inheritFrom'));
$cparams = new JParameter($masterCategory->params);
}
$params->merge($cparams);
//Category image
if (! empty($category->image)) {
$category->image = JURI::root().'media/k2/categories/'.$category->image;
} else {
if ($params->get('catImageDefault')) {
$category->image = JURI::root().'components/com_k2/images/placeholder/category.png';
}
}
//Category plugins
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin('content');
$category->text = $category->description;
$dispatcher->trigger('onPrepareContent', array ( & $category, &$params, $limitstart));
$category->description = $category->text;
//Category K2 plugins
$category->event->K2CategoryDisplay = '';
JPluginHelper::importPlugin('k2');
$results = $dispatcher->trigger('onK2CategoryDisplay', array(&$category, &$params, $limitstart));
$category->event->K2CategoryDisplay = trim(implode("\n", $results));
$category->text = $category->description;
$dispatcher->trigger('onK2PrepareContent', array ( & $category, &$params, $limitstart));
$category->description = $category->text;
//Category link
$link = urldecode(K2HelperRoute::getCategoryRoute($category->id.':'.urlencode($category->alias)));
$category->link = JRoute::_($link);
$category->feed = JRoute::_($link.'&format=feed');
JRequest::setVar('view', 'itemlist');
JRequest::setVar('task', 'category');
JRequest::setVar('id', $category->id);
JRequest::setVar('featured', 1);
JRequest::setVar('limit', $limit);
JRequest::setVar('clearFlag', true);
$category->name = htmlspecialchars($category->name, ENT_QUOTES);
$category->items = $model->getData('rdate');
JRequest::setVar('view', 'latest');
JRequest::setVar('task', '');
for ($i = 0; $i < sizeof($category->items); $i++) {
if ($user->guest){
$hits = $category->items[$i]->hits;
$category->items[$i]->hits = 0;
$category->items[$i] = $cache->call(array('K2ModelItem', 'prepareItem'), $category->items[$i], 'latest', '');
$category->items[$i]->hits = $hits;
}
else {
$category->items[$i] = $itemModel->prepareItem($category->items[$i], 'latest', '');
}
$category->items[$i] = $itemModel->execPlugins($category->items[$i], 'latest', '');
//Trigger comments counter event
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin ('k2');
$results = $dispatcher->trigger('onK2CommentsCounter', array ( & $category->items[$i], &$params, $limitstart));
$category->items[$i]->event->K2CommentsCounter = trim(implode("\n", $results));
}
$categories[]=$category;
}
}
}
$source = 'categories';
$this->assignRef('blocks', $categories);
} else {
$usersIDs = $params->get('userIDs');
if(is_string($usersIDs) && !empty($usersIDs)){
$usersIDs = array();
$usersIDs[]=$params->get('userIDs');
}
$users = array();
if(is_array($usersIDs)){
foreach($usersIDs as $userID){
$userObject = JFactory::getUser($userID);
if (!$userObject->block) {
//User profile
$userObject->profile = $model->getUserProfile($userID);
//User image
$userObject->avatar = K2HelperUtilities::getAvatar($userObject->id, $userObject->email, $params->get('userImageWidth'));
//User K2 plugins
$userObject->event->K2UserDisplay = '';
if (is_object($userObject->profile) && $userObject->profile->id > 0) {
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin('k2');
$results = $dispatcher->trigger('onK2UserDisplay', array(&$userObject->profile, &$params, $limitstart));
$userObject->event->K2UserDisplay = trim(implode("\n", $results));
}
$link = K2HelperRoute::getUserRoute($userObject->id);
$userObject->link = JRoute::_($link);
$userObject->feed = JRoute::_($link.'&format=feed');
$userObject->name = htmlspecialchars($userObject->name, ENT_QUOTES);
$userObject->items = $model->getAuthorLatest(0,$limit,$userID);
for ($i = 0; $i < sizeof($userObject->items); $i++) {
if ($user->guest){
$hits = $userObject->items[$i]->hits;
$userObject->items[$i]->hits = 0;
$userObject->items[$i] = $cache->call(array('K2ModelItem', 'prepareItem'), $userObject->items[$i], 'latest', '');
$userObject->items[$i]->hits = $hits;
}
else {
$userObject->items[$i] = $itemModel->prepareItem($userObject->items[$i], 'latest', '');
}
//Plugins
$userObject->items[$i] = $itemModel->execPlugins($userObject->items[$i], 'latest', '');
//Trigger comments counter event
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin ('k2');
$results = $dispatcher->trigger('onK2CommentsCounter', array ( & $userObject->items[$i], &$params, $limitstart));
$userObject->items[$i]->event->K2CommentsCounter = trim(implode("\n", $results));
}
$users[]=$userObject;
}
}
}
$source = 'users';
$this->assignRef('blocks', $users);
}
//Look for template files in component folders
$this->_addPath('template', JPATH_COMPONENT.DS.'templates');
$this->_addPath('template', JPATH_COMPONENT.DS.'templates'.DS.'default');
//Look for overrides in template folder (K2 template structure)
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2'.DS.'templates');
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2'.DS.'templates'.DS.'default');
//Look for overrides in template folder (Joomla! template structure)
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2'.DS.'default');
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2');
//Assign params
$this->assignRef('params', $params);
$this->assignRef('source', $source);
//Set layout
$this->setLayout('latest');
//Display
parent::display($tpl);
}
}
But this file is somehow used to retrieve items in using menu link. I am sorry if this is not the case.
In order to make this work the way you want you would have to modify the K2 item model. The data you want to display (recent items in category) is not currently being pulled from the database so you'd have to change to model to accommodate that. You would be much better off using the K2 content module to pull the most recent items instead. It wouldn't require hacking any core K2 code.
Also, you really need to update your software. K2 is on v2.5.4 and Joomla is on 2.5.1.