Decrement value in a loop - php

I am trying to make a query model where every time a query is posted, specific users are notified by mail and their records are decremented by 1.
Mail is working fine but the decrement is happening by the number of users identified and not 1.
Have tried various P&C.
$exclusive = DB::table('user_plans')
->leftJoin('companies', 'companies.id' , '=', 'user_plans.user_id')
->select('user_plans.*')
->where('user_plans.service_id' , '=', $input['project'])
->where('user_plans.lead_type' , '=', 2)
->where('user_plans.count' , '>', 0)
->limit(5)
->get();
$shared = DB::table('user_plans')
->leftJoin('companies', 'companies.id' , '=', 'user_plans.user_id')
->select('user_plans.*')
->where('user_plans.service_id' , '=', $input['project'])
->where('user_plans.lead_type' , '=', 1)
->where('user_plans.count' , '>', 0)
->limit(500)
->get();
$project = DB::table('services')
->select('services.*')
->where('services.id' , '=', $input['project'])
->get();
if (count($exclusive) > 0) {
foreach ($exclusive as $exclusive) {
Mail::send('emails.exclusive', array(
'name' => $input['name'],
'email' => $input['email'],
'phone' => $input['phone'],
'detail' => $input['detail'],
'project' => $project[0]->name,
'budget' => $input['budget']
), function($message) use ($exclusive) {
$message
->to($exclusive->lead_email)
->subject('CXO Forest Contact Us!');
});
//This part is not working
$deduct = DB::table('user_plans')
->where('user_plans.user_id' , '=', $exclusive->user_id)
->where('user_plans.count' , '>', 0)
->where('user_plans.type' , '=', 2)
//->get();
->decrement('count', 1);
}
} else {
if (count($shared) > 0) {
foreach ($shared as $shared) {
Mail::send('emails.exclusive', array(
'name' => $input['name'],
'email' => $input['email'],
'phone' => $input['phone'],
'detail' => $input['detail'],
'project' => $project[0]->name,
'budget' => $input['budget']
), function($message) use ($shared) {
$message
->to($shared->lead_email)
->subject('CXO Forest Contact Us!');
});
$deductx = DB::table('user_plans')
->where('user_plans.user_id' , '=', $shared->user_id)
->where('user_plans.count' , '>', 0)
->where('user_plans.type' , '=', 2)
->decrement('count', 1);
}
} else {
Mail::send('emails.exclusive', array(
'name' => $input['name'],
'email' => $input['email'],
'phone' => $input['phone'],
'detail' => $input['detail'],
'project' => $project[0]->name,
'budget' => $input['budget']
), function($message) use ($shared) {
$message
->to('amit.khare#studyspectrum.com')
->subject('Urgent: This lead does not have any takers');
});
}
}
Every time the code runs, deduct should reduce user_plans by 1 and not the number of emails sent.
Thanks guys for the help.

Here's the part part that is not working, try this:
DB::table('user_plans') ->where('user_plans.user_id' , '=', $exclusive->user_id) ->where('user_plans.count' , '>', 0) ->where('user_plans.type' , '=', 2) ->take(1)->delete();

Related

laravel 8 update eloquent relationships hasmany

My UPDATE function is as follows; I manually set some fields in the users table. In other words, it is necessary to update only the name part from the incoming request. If the lawyer has been removed from the edit form, it must also be removed from the users table. If the lawyer name has been updated, it should also be updated in the table.
How can I complete the update process.
public function update(Request $request, LegalPursuit $legalPursuit, $id)
{
$request->validate([
'BRANCH_ID' => 'required',
'MAIN_ACCOUNT_ID' => 'required',
'DEPOSITOR_ID' => 'required',
'ACCOUNT_HOLDER' => 'required|max:255',
'CURRENT_SCREEN_BALANCE' => 'required',
'TRL_EQUIVALENT' => 'required'
]);
//dd($request->all());
if($request->input('PROVISION') == 'on'){
$request->request->add(['PROVISION' => 'yes']);
}
$request->FOLLOW_UP_DATE = \Carbon\Carbon::parse($request->input('FOLLOW_UP_DATE'))->format('Y-m-d');
$request->DATE_OF_ATTORNEY_SUBMISSION = \Carbon\Carbon::parse($request->input('DATE_OF_ATTORNEY_SUBMISSION'))->format('Y-m-d');
$request->PROVISION_DATE = \Carbon\Carbon::parse($request->input('PROVISION_DATE'))->format('Y-m-d');
$request->request->add(['FOLLOW_UP_DATE' => $request->FOLLOW_UP_DATE]); //dd request
$request->request->add(['DATE_OF_ATTORNEY_SUBMISSION' => $request->DATE_OF_ATTORNEY_SUBMISSION]); //dd request
$request->request->add(['PROVISION_DATE' => $request->PROVISION_DATE]); //dd request
if(is_array($request->input('LAWYERS')) AND !empty($request->input('LAWYERS'))){
$lawyerArray = $request->input('LAWYERS');
//dd($lawyer_array);
$lawyerArray->each(function($lawyer) use ($user) {
$user->lawyerArray()->updateOrCreate(
[
'legalpursuit_id' => $id],
[
'role_id' => 1,
'name' => $request->input('LAWYERS'),
'email' => 'aa#'.rand().'.com',
'email_verified_at' => now(),
'password'=> Hash::make('1q2w3e4r'),
'department' => 'Avukat',
'gender' => 'Kadın',
'marital_status' => 'Bekar',
'job' => 'Avukat',
'phone' => '+9055555',
'internal_no' => '0',
'active' => '0',
'deleted' => '0'
]
);
}
);
for($x = 0; $x < count($request->input('LAWYERS')); $x++){
User::updateOrInsert(
['legalpursuit_id' => $id],
[
'role_id' => 1,
'name' => $request->input('LAWYERS'),
'email' => 'aa#'.rand().'.com',
'email_verified_at' => now(),
'password'=> Hash::make('1q2w3e4r'),
'department' => 'Avukat',
'gender' => 'Kadın',
'marital_status' => 'Bekar',
'job' => 'Avukat',
'phone' => '+9055555',
'internal_no' => '0',
'active' => '0',
'deleted' => '0'
]);
}
/*foreach($lawyer_array as $lawyer) {
$updateLaywer =
}
dd($updateLaywer);
/*
$getUsers = DB::table('users')
->select(['users.id'])
->leftJoin('legalpursuit', 'users.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->get();
$lawyersChanged = DB::table('users')
->whereIn('id', $getUsers)
->update(
[
'name' => ''
]
);
*/
//echo "asdfasdfasdf";exit;
/*
$lawyersChanged = User::updateOrCreate(
['legalpursuit_id' => $id],
['name' => $request->input('LAWYERS')]
);
//echo $lawyersChanged; exit;*/
}else{
$getUsers = DB::table('users')
->select(['users.id'])
->leftJoin('legalpursuit', 'users.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->get();
$getUsers->delete();
//echo "aaaaaaaa";exit;
}
if(is_array($request->input('GUARANTORS')) AND !empty($request->input('GUARANTORS'))){
echo "asdfasdfadsf";exit;
$guarantorsChanged = Guarantors::updateOrCreate(
['legalpursuit_id' => $id],
['name' => $request->input('GUARANTORS')]
);
}else{
//echo "hdfghdfghdfghdfgh";exit;
$getGuarantors = DB::table('guarantors')
->select(['guarantors.id'])
->leftJoin('legalpursuit', 'guarantors.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->delete();
//dd($getGuarantors);
//$getGuarantors->delete();
}
if($request->input('REMOVE_FILES')){
$getCurrentFiles = DB::table('files')
->select(['files.ID'])
->leftJoin('legalpursuit', 'files.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->delete();
}
LegalPursuit::where('ID',$id)->update(
$request->only(
[
'BRANCH_ID',
'MAIN_ACCOUNT_ID',
'DEPOSITOR_ID',
'ACCOUNT_HOLDER',
'FOLLOW_UP_DATE',
'CURRENT_SCREEN_BALANCE',
'CURRENCY',
'TRL_EQUIVALENT',
'DATE_OF_ATTORNEY_SUBMISSION',
'PROVISION',
'PROVISION_DATE',
'LAWSUIT_ID',
'ASSURANCE',
'DEED_PLATE',
'APPRAISAL_VALUE',
'LIEN_PRICE',
'DETERMINED_GUARANTEES',
'LEVY_INFO',
'LAST_STATUS'
]
)
);
if($request->hasFile('FILES')) {
foreach ($request->file('FILES') as $fl) {
$fileName = time().'_'.$fl->getClientOriginalName();
$fileExt = $fl->getClientOriginalExtension();
$filePath = $fl->store('public/files');
$filex = new Files;
$filex->legalpursuit_id = $id;
$filex->name = $fileName;
$filex->type = $fileExt;
$filex->label = $filePath;
$filex->descript = $fileName.'-'.$fileExt.'--'.$filePath;
$filex->status = 'on';
$filex->save();
}
}
return redirect()->back()->with('success', 'Kayıt Başarılı Bir Şekilde Güncellendi...');
}

creating a badge in the navbar and getting data from controller

I'm using laravel. I'm trying to create a badge in the navbar and getting the number of rows from a specific table in the database. I have the following codes for the navbar:
<span class='badge badge-pill badge-info'>
#php !empty(session('notifications.all2')) ? print(array_sum(session('notifications.all2'))) : ""
#endphp
</span>
and this for the controller:
class NotificationsController extends Controller
{
public function index ()
{
$settings = NotificationSettings::where('user_id', Auth::id())
->orderBy('name')
->get();
$user = User::where('id', auth::id())
->select('id')
->first();
if(count($settings) == 0)
{
$tasks = Tasks::all();
foreach ($tasks as $task)
{
NotificationSettings::create([
'user_id' => $user->id,
'name' => $task->name,
'module' => 'Task Schedule'
]);
$settings = NotificationSettings::where('user_id', Auth::id())
->orderBy('name')
->get();
}
}
$checkRestockTask = Tasks::where('name', 'Available Restock Inventory')->first();
if($checkRestockTask){
$checkUser = NotificationSettings::where('user_id', Auth::id())
->where('name', 'Available Restock Inventory')
->first();
if(!$checkUser){
NotificationSettings::create([
'user_id' => $user->id,
'name' => 'Available Restock Inventory',
'module' => 'Task Schedule'
]);
$settings = NotificationSettings::where('user_id', Auth::id())
->orderBy('name')
->get();
}
}
$data = [
'active' => 'settings',
'user_id' => $user->id,
'role' => $user->role_id ? $user->role_id : 'null',
'tasks' => $settings
]; //echo "<pre>"; print_r($data); echo "</pre>";
return view('notifications.index2')->with($data);
}
public function add ()
{
$data = array(
'active' => 'settings',
'user_id' => Auth::id(),
); //echo "<pre>"; print_r($data); echo "</pre>"; die();
return view('notifications.add')
->with($data);
}
public function saveNotification (Request $request)
{
$module = $request->get('module');
$user_id = $request->get('user_id');
$notification_name = $request->get('notification_name');
if($module == 1)
{
$module_name = 'Task Schedule';
}
$saved_notifs = NotificationSettings::where('user_id', $user_id)
->select('name')
->get();
$notif_names = array();
foreach ($saved_notifs as $saved_notif)
{
array_push($notif_names, $saved_notif->name);
}
if(in_array($notification_name, $notif_names))
{
return back()->with('error', 'Notification already added');
}
else
{
NotificationSettings::create([
'user_id' => $user_id,
'name' => $notification_name,
'module' => $module_name
]);
return redirect('notifications');
}
}
public function editNotification (Request $request, $user_id = null)
{
$checked_tasks = explode(',', $request->get('tasks'));
if(count($checked_tasks) > 0)
{
NotificationSettings::where('user_id', Auth::id())
->whereIn('name', $checked_tasks)
->update(['status' => 1]);
NotificationSettings::where('user_id', Auth::id())
->whereNotIn('name', $checked_tasks)
->update(['status' => 0]);
}
else
{
NotificationSettings::where('user_id', $user_id)
->update(['status' => 0]);
}
$settings = NotificationSettings::where('user_id', Auth::id())
->orderBy('name')
->get();
return json_encode($settings);
}
public function getTasks ()
{
$tasks = Tasks::select('name', 'id')
->orderBy('id')
->get();
$data = array(
'tasks' => $tasks,
); //echo "<pre>"; print_r($data); echo "</pre>"; die();
return $data;
}
public function viewAllNotifications ()
{
$user_id = Auth::id();
$view = Notification::where('recipient_id', $user_id)
->where('viewed', 0)
->update(['viewed' => 1]);
$notifications = Notification::where('recipient_id', $user_id)
->join('stores', 'stores.id', '=', 'notifications.store_id')
->select('notifications.content', 'notifications.recipient_id', 'notifications.url', 'notifications.read', 'notifications.viewed', 'stores.name', 'notifications.created_at', 'notifications.updated_at')
->orderBy('notifications.id', 'desc')
->paginate(25);
$data = array(
'active' => 'settings',
'notifications' => $notifications,
'user_id' => $user_id,
);
// return $data;
return view('notifications.all2')
->with($data);
}
public function getAllNotifications(Request $request){
$user_id = Auth::id();
$view = Notification::where('recipient_id', $user_id)
->where('viewed', 0)
->update(['viewed' => 1]);
$notifications = Notification::where('recipient_id', $user_id)
->join('stores', 'stores.id', '=', 'notifications.store_id')
->select('notifications.content', 'notifications.recipient_id', 'notifications.url', 'notifications.read', 'notifications.viewed', 'stores.name', 'notifications.created_at', 'notifications.updated_at')
->orderBy('notifications.id', 'desc')
->paginate(25);
return json_encode($notifications);
}
}
I just cant seem to get the number appear in the badge/pill that i have created. thanks for the answers in advance.

Laravel : How to get object in column with query builder

I want to display what kind of data I have described below, but I don't know the keywords.
For now, this is my data:
And this is the result I want:
This is, my controller:
$data = DB::table('tr_doctor_schedules as sch')
->select('sch.id as schedule_id','doctor_name','hospital_name','estimated_practice_time','day','from_time','until_time')
->join('mst_hospitals as hos', 'hos.id', '=', 'sch.hospital_id')
->join('mst_doctors as doc', 'doc.id', '=', 'sch.doctor_id')
->join('tr_doctor_schedule_details as dtl', 'dtl.doctor_schedule_id', '=', 'sch.id')
->where('sch.hospital_id', $hosId)
->where('sch.doctor_id', $docId)
->first();
if ($data) {
return response()->json([
'success' => true,
'message' =>'success',
'data' => $data
], 200);
} else {
return response()->json([
'success' => false,
'message' => 'Data not found.',
], 400);
}
Thanks
Try this
$data = DB::table('tr_doctor_schedules as sch')
->selectRaw('sch.id as schedule_id,doctor_name,hospital_name,estimated_practice_time,GROUP_CONCAT(day) as day,from_time,until_time')
->join('mst_hospitals as hos', 'hos.id', '=', 'sch.hospital_id')
->join('mst_doctors as doc', 'doc.id', '=', 'sch.doctor_id')
->join('tr_doctor_schedule_details as dtl', 'dtl.doctor_schedule_id', '=', 'sch.id')
->where('sch.hospital_id', $hosId)
->where('sch.doctor_id', $docId)
->groupBy('sch.id')
->first();

How do I unit-test table filter function in lumen

This is the my back-end code. I wrote the test for this function as follows:
public function index(Request $request)
{
$fields = 'in:' . implode(',', Schema::getColumnListing('suppliers'));
$messages = [
'order_by.in' => 'The selected column name is invalid.',
];
$this->validate($request, [
'page' => ['numeric'],
'per_page' => ['numeric'],
'order_direction' => ['in:desc,asc,DESC,ASC'],
'order_by' => [$fields],
], $messages);
$perPage = 10;
$filter = '';
$orderBy = 'id';
$orderDirection = 'DESC';
try {
if ($request->has('per_page')) $perPage = (int)$request->per_page;
if ($request->has('filter')) $filter = $request->filter;
if ($request->has('order_by')) $orderBy = $request->order_by;
if ($request->has('order_direction')) $orderDirection = strtoupper($request->order_direction);
$suppliers = Supplier::select('id', 'firstname', 'lastname', 'phone', 'email', 'custom_field_1', 'custom_field_2')->where('store_id', Auth::user()->store);
if (!!$filter) {
$suppliers->where('id', 'LIKE', "%{$filter}%")
->orWhere('firstname', 'LIKE', "%{$filter}%")
->orWhere('lastname', 'LIKE', "%{$filter}%")
->orWhere('email', 'LIKE', "%{$filter}%")
->orWhere('phone', 'LIKE', "%{$filter}%");
}
$suppliers->orderBy($orderBy, $orderDirection);
$suppliers = $suppliers->paginate($perPage);
return response()->json([
'success' => true,
'data' => $suppliers->toArray(),
], Response::HTTP_OK);
} catch (Exception $e) {
report($e);
return serverExceptionMessage();
}
}
This is what I have tried and test. I'm creating a store because store_id is a foreign key in my supplier table and adding suppliers dynamically and filtering the firstname through the URL and getting the result from seeJson as an array:
public function testSupplierListViewPaginationFilterTest()
{
$user = factory('App\Models\User')->make();
$store = (factory('App\Models\Store')->make())->getAttributes();
$this->actingAs($user)
->post('/create-new-store', $store)
->seeStatusCode(Response::HTTP_OK);
$attributes = [
'id' => 1,
'firstname' => 'ashid',
'lastname' => 'mhd',
'phone' => 776358547,
'email' => 'ashid#email.com',
'custom_field_1' => 'test',
'custom_field_2' => 'test',
];
$user->store = Store::latest()->first()->id;
$attributes['store_id'] = Auth::user()->store;
$supplier = Supplier::create($attributes);
$this->actingAs($user)
->get('/suppliers?filter=' . $supplier['firstname'], $attributes)
->seeStatusCode(Response::HTTP_OK)->seeJson([
'success' => true,
"data" =>
[
'id' => 1,
'firstname' => 'ashid',
'lastname' => 'mhd',
'phone' => 776358547,
'email' => 'ashid#email.com',
'custom_field_1' => 'test',
'custom_field_2' => 'test',
]
]);
}
I'm getting following error:
1) SupplierTest::testSupplierListViewPaginationFilterTest
Unable to find JSON fragment
["data":"custom_field_1":"test","custom_field_2":"test","email":"ashid#email.com","firstname":"ashid","id":1,"lastname":"mhd","phone":776358547}] within [{"data":{"current_page":1,"data":[{"custom_field_1":"test","custom_field_2":"test","email":"ashid#email.com","firstname":"ashid","id":1,"lastname":"mhd","phone":"776358547"}],"first_page_url":"http:\/\/localhost\/suppliers?page=1","from":1,"last_page":1,"last_page_url":"http:\/\/localhost\/suppliers?page=1","next_page_url":null,"path":"http:\/\/localhost\/suppliers","per_page":10,"prev_page_url":null,"to":1,"total":1},"success":true}].
Failed asserting that false is true.
I need a best solution for this problem .

"Trying to get property 'id' of non-object"

I want to get the id of the cycles table so that I can store to the mortalities table.
SELECT `id` FROM `cycles`
WHERE `date_start_raise` <= request('date_input')
AND `date_end_raise` >= request('date_input')`
Converted to Laravel Query Builder:
<?php
$cycle = DB::table('cycles')->select('id')
->where('date_start_raise', '<=', request('date_input'))
->where('date_end_raise', '>=', request('date_input'))
->get();
request('date_input') was from the MortalityController
MortalityController.php
public function store(Request $request)
{
$this->validate($request, array(
'date_input' => 'required|date',
'number_of_mortality' => 'required|numeric',
'chicken_age' => 'required|numeric'
) );
$cycle = DB::table('cycles')->select('id')
->where('date_start_raise', '<=', request('date_input'))
->where('date_end_raise', '>=', request('date_input')) ->get();
return Mortality::create([
'date_input' => request('date_input'),
'number_of_mortality' => request('number_of_mortality'),
'chicken_age' => request('chicken_age'),
'cause_of_death' => request('cause_of_death'),
'cycle_id' => $cycle->first()->id,
'user_id' => Auth::id()
]);
}
After that I got an error:
"message": "SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect
integer value: '[]' for column 'cycle_id' at row 1 (SQL: insert into
mortalities (date_input, number_of_mortality, chicken_age,
cause_of_death, cycle_id, user_id, updated_at, created_at)
values (2018-09-04, 25, 2, , [], 1, 2018-11-28 07:38:01, 2018-11-28
07:38:01))"
I fix the error but new error appeared
"message": "Trying to get property 'id' of non-object"
Can anyone please help me?
You need to get values from $request object by using $request->get('your_id') or
$request->input('your_id')
Try this..!!
$cycle = DB::table('cycles')->select('id')
->where('date_start_raise','<=',$request->get('date_input'))
->where('date_end_raise','>=',$request->get('date_input'))
->first();
OR
$cycle = DB::table('cycles')->select('id')
->where('date_start_raise','<=',$request->get('date_input'))
->where('date_end_raise','>=',$request->get('date_input'))
->get();
then
foreach($cycle as $value){
//extract data from $value
}
Hop its work for you ...
use like that (u are passing collection to insert)
$cycle = DB::table('cycles')->select('id')
->where('date_start_raise','<=',request('date_input'))
->where('date_end_raise','>=',request('date_input'))
->first()->id;
Check this !!
return Mortality::create([
'date_input' => request('date_input'),
'number_of_mortality' => request('number_of_mortality'),
'chicken_age' => request('chicken_age'),
'cause_of_death' => request('cause_of_death'),
'cycle_id' => $cycle->first()->id,
'user_id' => Auth::id()
]);`

Categories