Factory same ID for a column, auto-incremental, Laravel - laravel

I try to give to a column the ID of that row, witch is autoincremental. Right now are random values .
//From Factory
return [
//code...
'register_id' => $faker->unique()->numberBetween($min = 1, $max = 100),
//code...
];
//From Seeder
public function run()
{
factory(App\Person::class, 100)->create();
}

I found an answer, here , and I edited for my case.
$autoIncrement = autoIncrement();
$factory->define(Person::class, function (Faker $faker) use ($autoIncrement) {
$autoIncrement->next();
//code
return [
'register_id' => $autoIncrement->current(),
]
});
function autoIncrement()
{
for ($i = 0; $i < 1000; $i++) {
yield $i;
}
}

Related

How can I update a column value given a where clause in Laravel?

I've tried doing:
$uniquekey = '202208271120';
$results2 =DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', '0')
->update([ 'id_evento_test'=> $uniquekey]);
return response()->json($results2, 201);
but when testing it in postman returned me 0.
enter image description here
Here's my code:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class ShowSummaryResultsController extends Controller
{
public function show(Request $request)
{
$usuario = $request->input('usuario');
$results = DB::table('tests')
->where('usuario_id', '=', $usuario)
->where('id_evento_test', '=', '0')
->get();
$resultsOkPROTANOPIA = 0;
$resultsNokPROTANOPIA = 0;
$resultsOkDEUTERANOPIA = 0;
$resultsNokDEUTERANOPIA = 0;
$resultsOkTRITANOPIA = 0;
$resultsNokTRITANOPIA = 0;
foreach ($results as $rows)
{
$image_id = $rows->image_id;
$resultado = $rows->resultado;
//$tipo = DB::table('images')
//->where('id', '=', $image_id)
//->get();
$image = 'App\Models\Image'::findOrFail($image_id);
$tipo_discromatopsia = $image->tipo_discromatopsia;
if ($tipo_discromatopsia == 'PROTANOPIA') {
if($resultado) {
$resultsOkPROTANOPIA +=1;
}else{
$resultsNokPROTANOPIA +=1;
}
}
elseif ($tipo_discromatopsia == 'DEUTERANOPIA') {
if($resultado) {
$resultsOkDEUTERANOPIA +=1;
}else{
$resultsNokDEUTERANOPIA +=1;
}
}
else {
if($resultado) {
$resultsOkTRITANOPIA +=1;
}else{
$resultsNokTRITANOPIA +=1;
}
}
//update event_id with a unique key
//$uniquekey = 202208271116;
//$results->id_evento_test = $uniquekey;
//$results->save();
}
$porc=0;
if (($resultsOkPROTANOPIA + $resultsNokPROTANOPIA) >0)
{ $porc=$resultsOkPROTANOPIA / ($resultsOkPROTANOPIA + $resultsNokPROTANOPIA ) * 100; }
$result[0] = array("tipo" =>'PROTANOPIA',"ResOK" =>$resultsOkPROTANOPIA,"ResNOK" =>$resultsNokPROTANOPIA,"Porc" =>$porc);
$porc=0;
if (($resultsOkDEUTERANOPIA + $resultsNokDEUTERANOPIA ) >0)
{$porc=$resultsOkDEUTERANOPIA / ($resultsOkDEUTERANOPIA + $resultsNokDEUTERANOPIA ) * 100;}
$result[1] = array("tipo" =>'DEUTERANOPIA',"ResOK" =>$resultsOkDEUTERANOPIA,"ResNOK" =>$resultsNokDEUTERANOPIA,"Porc" =>$porc);
$porc=0;
if (($resultsOkTRITANOPIA + $resultsNokTRITANOPIA )>0)
{$porc=$resultsOkTRITANOPIA/ ($resultsOkTRITANOPIA + $resultsNokTRITANOPIA )* 100;}
$result[2] = array("tipo" =>'TRITANOPIA',"ResOK" =>$resultsOkDEUTERANOPIA,"ResNOK" =>$resultsNokDEUTERANOPIA,"Porc" =>$porc);
$min = min($result[0]['Porc'],$result[1]['Porc'],$result[2]['Porc']);
$result[3] = array("tipo" =>'RESULTADOS',"index"=>$min,"Tipo"=>$result[$min]['tipo'], );
$uniquekey = '202208271120';
$results2 =DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', '0')
->update([ 'id_evento_test'=> $uniquekey]);
return response()->json($results2, 201);
//return response()->json($result, 201);
}
}
If you need value of column after successful updating then read this example please:
$uniquekey = '202208271120';
try {
DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', 0)
->update(['id_evento_test' => $uniquekey]);
$results2 = $uniquekey;
return response()->json($results2, 201);
} catch (\Illuminate\Database\QueryExeption $e) {
return response()->json(['error' => 'Unsuccessful Update']);
}
You can use first or get to retrieve all the data from table test or only column id_evento_test. So $results2 could have all data or only part of data as you need.
in this code $results2 =DB::table('tests') you are storing the result of the database query to $result2 which is 0 or 1 and 0 means that nothing was updated and 1 means that the update was done successfully.
if you want to return the $uniquekey then assign it to $result2:
$results2 = $uniquekey;
return response()->json($results2, 201);
or just return $uniquekey:
return response()->json($uniquekey, 201);

Laravel export Maatwebsite/Excel, restructuring the output

Could somebody tell me how to reformat the excel output, so that i get two excel columns. Right now it gives me two arrays in A1 and B1. like two fields with [1,24,5,3.3] and [3,4,5,6], but I want two columns with the numbers.
Route
Route::get('/exporttable/{id}', [TableExportController::class, 'export']);
TableExportController
use Illuminate\Http\Request;
use App\Exports\TablesExport;
use Maatwebsite\Excel\Facades\Excel;
class TableExportController extends Controller
{
public function export(Request $request){
return Excel::download(new TablesExport($request->id), 'tables.xlsx');
}
}
TableExport.php
use App\Models\Tabula;
use Maatwebsite\Excel\Concerns\FromCollection;
class TablesExport implements FromCollection
{
/**
* #return \Illuminate\Support\Collection
*/
function __construct($id) {
$this->id = $id;
}
public function collection()
{
$tabula = Tabula::select('soll', 'haben')->where('id', '=', $this->id)->get();
return $tabula;
}
}
It works with the code of Natvarsinh Parmar - bapu , if you edit the map-function like this
public function map($tabula): array
{
//unformatieren
$soll = $tabula->soll;
//vom string Randwerte abschneiden: [ und ]
$soll = substr($soll, 1, -1);
// in Array umwandeln
$soll = explode( ',', $soll);
//das gleiche mit soll
$haben = $tabula->haben;
$haben = substr($haben, 1, -1);
$haben = explode( ',', $haben);
// als ersten Wert den Header soll/haben einfügen ins Array
array_unshift($haben, "haben");
array_unshift($soll, "soll");
return [
$soll,
$haben
];
}
So now it works, thanks! Each array covers a row in excel now.
Make changes as per below in TableExport.php and check
<?php
namespace App\Exports;
use App\Models\Tabula;
use Maatwebsite\Excel\Concerns\FromArray;
class TablesExport implements FromArray
{
protected $soll;
protected $haben;
protected $export_data;
public function __construct($id)
{
$this->id = $id;
}
public function array(): array
{
$results = Tabula::select('id', 'soll', 'haben')
->where('id', $this->id)
->get();
$this->export_data = [];
$results->each(function($result) {
preg_match_all('!\d+!', $result->soll, $matches_soll);
preg_match_all('!\d+!', $result->haben, $matches_haben);
$this->soll = [];
$this->haben = [];
if(isset($matches_soll[0]))
{
$this->soll = collect($matches_soll[0]);
}
if(isset($matches_haben[0]))
{
$this->haben = collect($matches_haben[0]);
}
if(count($this->soll) > count($this->haben)) {
foreach($this->soll as $key => $val){
$temp = [];
$temp = [
$val,
(isset($this->haben[$key])) ? $this->haben[$key] : ''
];
$this->export_data[] = $temp;
}
} else {
foreach($this->haben as $key => $val){
$temp = [];
$temp = [
(isset($this->soll[$key])) ? $this->soll[$key] : '',
$val
];
$this->export_data[] = $temp;
}
}
});
return $this->export_data;
}
}

Laravel Livewire Calculate Trade Analytics

I'm working on a project where I need to calculate user trading analytics and update it on the user dashboard. Everything went smooth until the number of each user trades grew in number (total of 10.000 trades and above) which increase the load time. Is there a way to speed up the process?
My current code:
AnalyticsIndex.php
public function updateChart()
{
$trades = $this->filterTrades();
$tradeAnalyticsService = app(TradeAnalyticsService::class, ['trades' => $trades, 'balance' => $this->portfolio->balance]);
$this->netProfitData = $tradeAnalyticsService->getRangeNetProfit();
$this->winLoseData = $tradeAnalyticsService->getWinLossPercentage();
$this->bestTradeReturn = $tradeAnalyticsService->getBestTradeReturn();
$this->worstTradeReturn = $tradeAnalyticsService->getWorstTradeReturn();
$this->essentialsData = $tradeAnalyticsService->getEssentialsData();
$this->emit('updateData');
}
public function filterTrades()
{
$trades = $this->portfolio->trades(['return', 'return_percentage', 'status', 'entry_date', 'id', 'instrument'])->latest('entry_date')->get();
// $trades = Trade::select(['return', 'return_percentage', 'status', 'entry_date', 'id'])->where('portfolio_id', $this->portfolio->id)->orderBy('entry_date')->get();
switch ($this->filter) {
case '7D':
return $trades->where('entry_date', '<=', now()->endOfWeek())->where('entry_date', '>=', now()->startOfWeek());
break;
case '1M':
return $trades->where('entry_date', '<=', now()->endOfMonth())->where('entry_date', '>=', now()->startOfMonth());
break;
case '3M':
return $trades->where('entry_date', '<=', now()->endOfMonth())->where('entry_date', '>=', now()->startOfMonth()->subMonths(2));
break;
case '6M':
return $trades->where('entry_date', '<=', now()->endOfMonth())->where('entry_date', '>=', now()->startOfMonth()->subMonth(5));
break;
case '1Y':
return $trades->where('entry_date', '<=', now()->endOfYear())->where('entry_date', '>=', now()->startOfYear());
break;
case '2Y':
return $trades->where('entry_date', '<=', now()->endOfYear())->where('entry_date', '>=', now()->startOfYear()->subYears(1));
break;
case '3Y':
return $trades->where('entry_date', '<=', now()->endOfYear())->where('entry_date', '>=', now()->startOfYear()->subYears(2));
break;
case 'All':
return $trades;
break;
default:
return $trades;
break;
}
}
TradeAnalyticsService.php
<?php
namespace App\Services;
use App\Models\Portfolio;
use stdClass;
class TradeAnalyticsService
{
private $trades;
private $balance = 0;
public function __construct($trades, int $balance)
{
$this->trades = $trades;
$this->balance = $balance;
}
public function getNetProfit()
{
return $this->netProfit($this->trades);
}
public function getProfitFactor()
{
$win = $this->filterTrade('win')->sum('return');
$lose = abs($this->filterTrade('lose')->sum('return'));
if ($win < 1 || $lose < 1) {
return 0;
}
return $win / $lose;
}
public function getPercentProfitable()
{
$winCount = $this->filterTrade('win')->count();
$winLoseCount = $this->trades->whereIn('status', ['win', 'lose'])->count();
if ($winCount < 1 || $winLoseCount < 1) {
return 0;
}
return $winCount / $winLoseCount * 100;
}
public function getAverageTradeNetProfit()
{
$winLoseCount = $this->trades->whereIn('status', ['win', 'lose'])->count();
if ($winLoseCount < 1) {
return 0;
}
return $this->getNetProfit() / $winLoseCount;
}
public function getAverageWinner()
{
$sum = $this->filterTrade('win')->sum('return');
$count = $this->filterTrade('win')->count();
// dd($sum, $count);
if ($count < 1) {
return 0;
}
return $sum / $count;
}
public function getAverageLoser()
{
$sum = $this->filterTrade('lose')->sum('return');
$count = $this->filterTrade('lose')->count();
// dd($sum, $count);
if ($count == 0) {
return 0;
}
return $sum / $count;
}
public function getBestTradeReturn()
{
return $this->trades->sortByDesc('return')->first();
}
public function getWorstTradeReturn()
{
return $this->trades->sortBy('return')->first();
}
public function getWinCount()
{
return $this->filterTrade('win')->count();
}
public function getLoseCount()
{
return $this->filterTrade('lose')->count();
}
public function getTradeCount()
{
return $this->trades->count();
}
public function getBalanceGrowth()
{
return $this->balanceGrowth($this->trades);
}
public function getBalanceGrowthPercentage()
{
return $this->balanceGrowthPercentage($this->balanceGrowth($this->trades));
}
public function getEssentialsData()
{
return [
'profit_factor' => $this->getProfitFactor(),
'percent_profitable' => $this->getPercentProfitable(),
'average_trade_net_profit' => $this->getAverageTradeNetProfit(),
'trade_count' => $this->getTradeCount(),
'net_profit' => $this->getNetProfit(),
'longest_win_streaks' => $this->getLongestWinStreaks(),
'longest_lose_streaks' => $this->getLongestLoseStreaks(),
'average_winner' => $this->getAverageWinner(),
'average_loser' => $this->getAverageLoser(),
];
}
public function getWinLossPercentage()
{
$winCount = $this->filterTrade('win')->count();
$loseCount = $this->filterTrade('lose')->count();
if ($winCount + $loseCount == 0) {
return 0;
}
$win = $winCount / ($winCount + $loseCount) * 100;
$data = [
[
'x' => 'Win',
'y' => $win
],
[
'x' => 'Lose',
'y' => 100 - $win
]
];
$data = [$win, 100 - $win];
return $data;
}
public function getRangeNetProfit()
{
$data = array();
$trades = $this->trades->whereIn('status', ['win', 'lose']);
$rawDatas = $trades->groupBy(function ($item) {
return format_string_date($item->entry_date, 'd/m/y');
});;
if ($rawDatas->count() > 30) {
$rawDatas = $trades->groupBy(function ($item) {
return format_string_date($item->entry_date, 'm/y');
});;
}
foreach ($rawDatas as $key => $rawData) {
$tempData = [
'x' => $key,
'y' => $this->netProfit($rawData)
];
array_push($data, $tempData);
}
return $data;
}
public function getLongestWinStreaks()
{
$currentStreak = 0;
$longestStreak = 0;
foreach ($this->trades->whereIn('status', ['win', 'lose']) as $trade) {
if (!($trade->status == "win")) {
$currentStreak = 0;
continue;
}
$currentStreak++;
if ($currentStreak > $longestStreak) {
$longestStreak = $currentStreak;
}
}
return $longestStreak;
}
public function getLongestLoseStreaks()
{
$currentStreak = 0;
$longestStreak = 0;
foreach ($this->trades->whereIn('status', ['win', 'lose']) as $trade) {
if (!($trade->status == "lose")) {
$currentStreak = 0;
continue;
}
$currentStreak++;
if ($currentStreak > $longestStreak) {
$longestStreak = $currentStreak;
}
}
return $longestStreak;
}
private function balanceGrowth($trades)
{
return $this->balance + $trades->sum('return');
}
private function balanceGrowthPercentage($balance)
{
$initial = $this->balance;
if ($initial <= 0) {
return 0;
}
return ($balance - $initial) / $initial * 100;
}
private function netProfit($trades)
{
return $trades->whereIn('status', ['win', 'lose'])->sum('return');
}
private function filterTrade(string $status)
{
return $this->trades->where('status', $status);
}
}
Note: The data is calculated once with wire:init and every time the user clicks on the filter button (7D, 1M, 3M, etc)

PhpStorm cannot track some file changes

I have noticed that some of my files in PhpStorm does not detect any changes while in other files I can see the changes immediately if I did some code changes.
Is there a way to find where in the PhpStorm settings to auto-detect all files edited?
I've already checked my .gitignore file but I can't see the untrackable file isn't there.
For instance, in my UserScopeTrait.php file, I did code changes and I've seen changes automatically when I git status. but in my UserTrait.php file if I made changes in it there are no changes found.
Here are the exact files I've made some changes:
This is the UserScopeTrait.php file and this can be auto detected file changes:
<?PHP
namespace App\Traits;
use App\Jobs\SendEmployeeInvitationEmail;
use App\Jobs\SendEmployeeInvitationMondayTuesdayJob;
use App\Jobs\UpdateAdminEmployeeSurvey;
use App\Language;
use App\Location;
use App\LocationManager;
use App\Mail\SendWeeklySurvey;
use App\Mail\SurveyResultsAvailableNotification;
use App\Mail\SurveySentNotification;
use App\Repositories\UserCompanyRepository;
use App\Survey;
use App\Team;
use App\TeamManager;
use App\User;
use App\UserCompany;
use App\UsersAnswer;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Mail;
trait UserScopeTrait
{
public function scopeDispatchEmployeeInvites($query)
{
$users = $query->whereHas('userCompany', function ($company) {
$company->where('company_id', auth()->user()->company->id)->where('role_name', 'employee');
})->where('invite_sent', 0)->get();
$auth = auth()->user();
$dispatcher = new User();
$toSend = 0;
$notifyState = [];
// this is the changes I've made
adsfdsfasdfas
if ($users->count() == 5) {
/**
* first survey batch send
* date of action: all days except Monday, Tuesday
* send invitation & update survey details for admin and then mimic admin survey details to employee
*/
if (!Carbon::now()->isMonday() && !Carbon::now()->isTuesday()) {
$this->updateSurveyDetailsAdminEmployee(null, $auth, 'admin');
}
}
foreach ($users as $employee) {
$notifyState['total'] = $users->count();
$employee->invite_sent = true;
$employee->save();
$toSend++;
if ($notifyState['total'] == $toSend) {
$notifyState['last'] = true;
// Admin receive an email notification about surveys sent
$dispatcher->dispatchAdminSurveySentNotification($auth);
} else {
$notifyState['last'] = false;
}
/**
* counter reaches to 5 this means that this is the first survey
* and should update survey details for both admin & employee
*/
if ($users->count() == 5) {
if (Carbon::now()->isMonday()||Carbon::now()->isTuesday()) {
/**
* first survey batch send
* date of action: Monday, Tuesday
* send invitation only
*/
SendEmployeeInvitationMondayTuesdayJob::dispatch($employee, auth()->user())->onQueue('notification');
} else {
/**
* first survey batch send
* date of action: all days except Monday, Tuesday
* send invitation & mimic admin survey details to employee
*/
$this->updateSurveyDetailsAdminEmployee($employee, $auth, 'employee');
SendEmployeeInvitationEmail::dispatch($auth, $employee, $notifyState)->onQueue('notification');
}
}
/**
* not first survey batch & single execution
*/
else {
if ($users->count() >=2 && $users->count() <= 3) {
/**
* not first survey batch execution
* date of action: Monday, Tuesday
* send invitation only
*/
if (Carbon::now()->isMonday()||Carbon::now()->isTuesday()) {
SendEmployeeInvitationMondayTuesdayJob::dispatch($employee, auth()->user())->onQueue('notification');
}
/**
* not first survey batch execution
* date of action: all days except Monday, Tuesday
* send invitation & update survey details for employee only mimic admin survey details
*/
else {
$this->updateSurveyDetailsAdminEmployee($employee, $auth, 'employee');
SendEmployeeInvitationEmail::dispatch($auth, $employee, $notifyState)->onQueue('notification');
}
}
if ($users->count() == 1) {
/**
* not first survey single execution
* date of action: Monday, Tuesday
* send invitation only
*/
if (Carbon::now()->isMonday()||Carbon::now()->isTuesday()) {
SendEmployeeInvitationMondayTuesdayJob::dispatch($employee, auth()->user())->onQueue('notification');
}
/**
* not first survey single execution
* date of action: all days except Monday, Tuesday
* send invitation & update survey details for employee mimic admin survey details
*/
else {
$this->updateSurveyDetailsAdminEmployee($employee, $auth, 'employee');
SendEmployeeInvitationEmail::dispatch($auth, $employee, $notifyState)->onQueue('notification');
}
}
}
}
}
private function updateSurveyDetailsAdminEmployee($employee, $auth, $type)
{
$currentDate = Carbon::now();
$nextSurveyDate = clone $currentDate;
if ($type == 'admin') {
date_default_timezone_set($auth->timezone);
// Set next_survey_date base on account owner survey frequency setting
if ($auth->account->survey_frequency == 'every_week_wednesday') {
$nextSurveyDate = $nextSurveyDate->next(Carbon::WEDNESDAY);
} else {
$nextSurveyDate = $nextSurveyDate->next(Carbon::WEDNESDAY)->next(Carbon::WEDNESDAY);
}
// Update survey_date and next_survey_number for admin
$auth->current_survey_date = $currentDate;
$auth->next_survey_date = $nextSurveyDate;
$auth->first_survey = true;
$auth->next_survey_number = (new User())->getNextSurveyNumber($auth);
$auth->save();
}
else if ($type == 'employee') {
date_default_timezone_set($employee->timezone);
// Update next_survey_date and next_survey_number for employee
$employee->next_survey_date = $auth->next_survey_date;
$employee->current_survey_id = $auth->current_survey_id;
$employee->current_survey_date = $currentDate;
$employee->next_survey_number = $auth->next_survey_number;
$employee->invite_sent_time = now()->toDateTimeString();
$employee->save();
}
}
public function scopeUpdateMessageNotificationCounter($query, $data)
{
$managers = $query->whereHas('userCompany', function ($userCompany) use ($data) {
$userCompany->where('company_id', (new User())->authUserCompanyId())->where('role_name', 'manager');
})->get();
foreach ($managers as $user) {
$user->wait_for_my_reply = $data['waitingForMyReply'];
$user->wait_for_employee_organization_reply = $data['waitingForEmployeeOrganizationReply'];
$user->save();
}
$admin = User::whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
$admin->wait_for_my_reply = $data['waitingForMyReply'];
$admin->wait_for_employee_organization_reply = $data['waitingForEmployeeOrganizationReply'];
$admin->save();
}
public function scopeUserHasSurvey($query, $id)
{
$currentSurveyDate = $query->find($id)->current_survey_date;
$nextSurveyDate = $query->find($id)->next_survey_date;
if ($currentSurveyDate != null && $nextSurveyDate != null) {
return true;
} else {
return false;
}
}
public function scopeUserCompanyId($query, $id)
{
return $query->find($id)->company->id;
}
public function scopeUserCurrentSurveyId($query, $id)
{
return $query->find($id)->current_survey_id;
}
public function scopeFilterAdminAccess()
{
if (auth()->user()->freeze_account > 0 && auth()->user()->role_name == 'admin') {
return redirect()->route('billing')->with(['info' => 'Your account is freeze']);
}
}
public function scopeActiveAdmin($query)
{
$query = $query->role('admin')->where('freeze_account', 0);
$query = $query->whereNotNull('email_verified_at')->where('active', 1)->get();
return $query;
}
public function scopeTrialGracePeriodActiveAdmin($query)
{
return $query->role('admin')
->where('freeze_account', 0)
->whereNotNull('email_verified_at')
->where('active', 1)
->where('trial_grace_period', true);
}
public function scopeActiveEmployee($query, $companyId)
{
$query = $query->whereHas('roles', function ($roles) {
$roles->where('name', 'employee');
});
$query = $query->whereNotNull('email_verified_at')->where('active', 1);
$query = $query->whereHas('userCompany', function ($userCompany) use ($companyId) {
$userCompany->where('company_id', $companyId);
})->get();
return $query->count();
}
public function scopeAdminReplies($query)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
return $query->total_replies;
}
public function scopeIncrementReplies($query, $message)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
if (!is_null($message)) {
$query->increment('total_replies');
}
}
public function scopeSendSurveyResultNotification($query)
{
$user = new User();
$admin = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
// process survey result for admin
$user->processSurveyResult($admin);
$managers = User::whereHas('userCompany', function ($userCompany) use ($admin) {
$userCompany->where('company_id', $admin->company->id)->where('role_name', 'manager');
})->get();
if ($managers->count() > 0) {
foreach ($managers as $manager) {
// process survey result for manager
$user->processSurveyResultManager($manager);
}
}
}
public function scopeIncrementUserColumn($query, $column)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
switch ($column) {
case 'surveys_completed':
$query->increment('surveys_completed');
break;
case 'email_notification_sent':
$query->increment('email_notification_sent');
break;
case 'cheers_sent':
$query->increment('cheers_sent');
break;
case 'resolved_issues':
$query->increment('resolved_issues');
break;
case 'total_answers':
$query->increment('total_answers');
break;
case 'uncompleted_replies':
$query->increment('uncompleted_replies');
break;
case 'add_more':
$query->increment('add_more');
break;
}
}
public function scopeDecrementUserColumn($query, $column)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
switch ($column) {
case 'uncompleted_replies':
$query->decrement('uncompleted_replies');
break;
}
if ($query->uncompleted_replies < 1) {
$query->add_more = 0;
$query->save();
}
}
public function scopeDecrementResolvedIssues($query)
{
$query = $query->whereHas('company', function ($company) {
$company->where('id', (new User())->authUserCompanyId());
})->first();
$query->decrement('resolved_issues');
}
public function scopeGetUserEmployeeId($query)
{
$query = $query->whereHas('roles', function ($q) {
$q->where('name', 'employee');
})->get();
$query = $query->pluck('id');
return $query;
}
public function sendSurvey($query)
{
$users = User::get();
foreach ($users as $user) {
if ($user->employees >= 5) {
// Get all employees where company is equal to $this->user
$userId = UserCompany::where('company_id', $user->company->id)->pluck('user_id');
}
}
}
public function scopeGetCompanyId($query, $userId)
{
$query = $query->find($userId)->userCompany->company_id;
return $query;
}
public function scopeGetSurveyCompleted($query)
{
$users = User::whereHas('roles', function ($role) {
$role->where('name', 'admin');
});
}
public function scopeGetCurrentSurveyDetails($query, $request = null)
{
$companyId = null;
$userAnswerFilter = new UsersAnswer();
if (!is_null($request)) {
// this is checking request parameters from super admin's vibe monitor
if (isset($request['id'])) {
$user = $query->find($request['id']);
} else {
$user = $query->find(auth()->id());
}
} else {
$user = $query->find(auth()->id());
}
if ($user->role_name == 'admin') {
$companyId = $user->company->id;
} elseif ($user->role_name == 'manager') {
$companyId = $user->userCompany->company_id;
}
$employeeCount = UserCompany::where('company_id', $companyId)
->where('role_name', 'employee')
->where('last_login_at', '!=', null);
$surveyCompleted = UserCompany::where('company_id', $companyId)
->where('role_name', 'employee')
->where('survey_completed', true);
$userAnswerFilter->filter($request, $surveyCompleted);
$userAnswerFilter->filter($request, $employeeCount);
$surveyCompleted = $surveyCompleted->count();
$employeeCount = $employeeCount->count();
if ($surveyCompleted > 0) {
$completionPercentage = round(($surveyCompleted / $employeeCount) * 100);
} else {
$completionPercentage = 0;
}
// date_default_timezone_set($user->timezone);
$now = Carbon::now();
$start = Carbon::parse($user->current_survey_date);
$end = Carbon::parse($user->current_survey_date)->next(Carbon::TUESDAY)->endOfDay();
// $end = $user->next_survey_date;
// $surveyStarts = Carbon::parse($start);
$surveyStarts = Carbon::parse($start)->format('Y-m-d');
// $surveyEnds = Carbon::parse($end);
$surveyEnds = Carbon::parse($end)->format('Y-m-d');
$now = Carbon::parse($now);
// $start = Carbon::parse($start);
// $end = Carbon::parse($end);
$diff = $end->diffInDays($now);
$status = $diff > 1 ? ('(' . $diff . ' days left)') : ('(' . $diff . ' day left)');
// $start = Carbon::parse($start)->isoFormat('LL');
// $end = Carbon::parse($end)->isoFormat('LL');
return [
'surveyId' => $user->current_survey_id,
'employeeCount' => $employeeCount,
'surveyCompleted' => $surveyCompleted,
'completionPercentage' => $completionPercentage,
'status' => $status,
'difference' => $diff,
'start' => $start->isoFormat('LL'),
'end' => $end->isoFormat('LL'),
'surveyStarts' => $surveyStarts,
'surveyEnds' => $surveyEnds
];
}
public function scopeGetUpcomingSurveyDetails($query, $userId = null)
{
$uId = $userId ?? auth()->id();
$auth = $query->find($uId);
// $surveyStarts = Carbon::createFromFormat('m-d-Y', $auth->next_survey_date);
$surveyStarts = Carbon::parse($auth->next_survey_date);
// Set survey ends base on account owner survey frequency setting
if ($auth->account->survey_frequency == 'every_week_wednesday') {
// $surveyEnds = $surveyStarts->addDays(7)->format('m-d-Y');
$surveyEnds = $surveyStarts->next(Carbon::TUESDAY)->endOfDay();
} else {
// $surveyEnds = $surveyStarts->addDays(14)->format('m-d-Y');
$surveyEnds = $surveyStarts->next(Carbon::TUESDAY)->next(Carbon::TUESDAY)->endOfDay();
}
// $now = Carbon::now()->format('m-d-Y');
$start = $auth->next_survey_date;
$end = $surveyEnds;
$now = Carbon::now();
$start = Carbon::parse($auth->next_survey_date);
$end = Carbon::parse($end);
$dateStartDbFormat = $auth->next_survey_date;
$dateEndDbFormat = $end;
$diff = $end->diffInDays($now);
$status = $diff > 1 ? ('(' . $diff . ' days left)') : ('(' . $diff . ' day left)');
$start = Carbon::parse($start)->isoFormat('LL');
$end = Carbon::parse($end)->isoFormat('LL');
return [
'surveyId' => $userId != null ? 'this is for email notification' : (new User())->authUserNextSurveyId(),
'status' => $status,
'start' => $start,
'dateStartDbFormat' => $dateStartDbFormat,
'dateEndDbFormat' => $dateEndDbFormat,
'end' => $end
];
}
public function scopeGetUpcomingSurveyDetails2($query)
{
$auth = $query->find(auth()->id());
$surveyStarts = Carbon::createFromFormat('m-d-Y', $auth->next_survey_date);
// Set survey ends base on account owner survey frequency setting
if ($auth->account->survey_frequency == 'every_week_wednesday') {
$surveyEnds = $surveyStarts->addDays(7)->format('m-d-Y');
} else {
$surveyEnds = $surveyStarts->addDays(14)->format('m-d-Y');
}
$now = Carbon::now()->format('m-d-Y');
$start = $auth->next_survey_date;
$end = $surveyEnds;
$now = Carbon::createFromFormat('m-d-Y', $now);
$start = Carbon::createFromFormat('m-d-Y', $start);
$end = Carbon::createFromFormat('m-d-Y', $end);
$dateStartDbFormat = $auth->next_survey_date;
$dateEndDbFormat = $end->format('m-d-Y');
$diff = $end->diffInDays($now);
$status = $diff > 1 ? ('(' . $diff . ' days left)') : ('(' . $diff . ' day left)');
$start = Carbon::parse($start, 'Asia/Manila')->isoFormat('LL');
$end = Carbon::parse($end, 'Asia/Manila')->isoFormat('LL');
return [
'surveyId' => (new User())->authUserNextSurveyId(),
'status' => $status,
'start' => $start,
'dateStartDbFormat' => $dateStartDbFormat,
'dateEndDbFormat' => $dateEndDbFormat,
'end' => $end
];
}
public function scopeGetPastSurveys($query)
{
$auth = $query->find(auth()->id());
$currentSurveyDate = Carbon::createFromFormat('m-d-Y', $auth->current_survey_date);
}
public function scopeAccountNotificationsSchedule($query, $schedule)
{
$users = $query->where('email_verified_at', '!=', null)->where('active', 1)->get();
foreach ($users as $user) {
$notification = $user->account->notifications['new_message'] ?? null;
if ($notification) {
$frequency = null;
switch ($notification) {
case 'every_10_minutes':
$frequency = 'everyTenMinutes';
break;
case '1x_per_hour':
$frequency = 'hourly';
break;
case '1x_per_day':
$frequency = 'daily';
break;
default:
break;
}
if ($user->total_replies != $user->new_messages_notification) {
$schedule->call(function () use ($user, $frequency) {
$language = $user->language;
$newMessages = $user->new_messages_notification;
$totalReply = $user->total_replies;
if ($newMessages > 1) {
$newMessages = $totalReply - $newMessages;
} else {
$newMessages = $user->total_replies;
}
if ($user->account->language_setting) {
$language = Language::find($user->account->language_setting)->language;
}
/** this should have job to avoid rapid sending of email that spikes email service provider */
Mail::to($user)->locale($language)->send(new \App\Mail\SendNewMessagesNotification($user, $newMessages));
$user->new_messages_notification = $user->total_replies;
$user->save();
})->$frequency();
}
}
}
}
}

Create public funtion in controller using for loop laravel

I am trying to create public funtions using for loop
here is an example about what I want to do:
class databaseController extends Controller
{
for ($i=0; $i < 5; $i++) {
# code...
public function create()
{
// dd('hoi_tb1_create');
if (Auth::guard('admin')->user()->level == 2) {
Schema::connection('mysql')->create('tb' . $i, function (
$table
) {
$table->increments('id');
});
}
// get all products
}
}
}
have you any idea how to do that?
Thanks in advance
Somur
You could use a second function to get this to work
class LoopController extends Controller
{
public function create($i)
{
if (Auth::guard('admin')->user()->level == 2) {
Schema::connection('mysql')->create('tb' . $i, function ($table) {
$table->increments('id');
});
}
}
public function createMany()
{
for($i = 0; $i < 5; $i++) {
$this->create($i);
}
}
}
The create function takes in a parameter of $i, but is not called directly from the route, instead you'd call createMany() which has a for loop in it. This will call create 5 times, each time passing its iterater value in e.g. 0, 1, 2, 3, 4.
Alternatively, if you're wanting these functions to be invoked independently, you could use PHP's magic method to dynamically call the create function. For example you could grab all of the numbers after create and then call create(numbers);
class LoopController extends Controller
{
public function create($i)
{
if (Auth::guard('admin')->user()->level == 2) {
Schema::connection('mysql')->create('tb' . $i, function ($table) {
$table->increments('id');
});
}
}
public function __call($method, $parameters)
{
if (preg_match('/create([\d]+)/', $method, $matches)) {
return $this->create($matches[1]);
}
throw new \BadMethodCallException("Method " . get_class($this) . "::$method does not exist");
}
}
So now if you call LoopController->create48(); It will then call ->create(48);

Resources