How to Automatically update expiry date from month in laravel? - ajax

I have to update the expiry date by counting from the month. Please guide me. While saving data expiry date is working fine. But I don't understand how to update it.
My Controller Code For Save Data
public function pay_success(Request $request){
$input = $request->all();
date_default_timezone_set('asia/calcutta');
$input['months'] = $request->months;
$expiry_date = Carbon::now()->addMonths($input['months']);
$input['expiry_date'] = $expiry_date;
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
//Send Email
$email = $input['email'];
$messageData = ['email' =>$input['email'],'name' =>$input['name'],'package' =>$input['package'],'months' =>$input['months'],'amount' =>$input['amount'],'expiry_date' =>$input['expiry_date']];
Mail::send('emails.mail',$messageData,function($message) use($email){
$message->to($email)->subject('Registration with AddSpy');
});
$arr = array('msg' => 'Payment successful.', 'status' => true);
return Response()->json($arr);
}
My Update Code is
public function update(Request $request) {
date_default_timezone_set('asia/calcutta');
$months = $request->months;
$expiry_date = Carbon::now()->addMonths($months);
$request['expiry_date'] = $expiry_date;
$data = ['id'=>$request->id, 'name'=>$request->name, 'phone'=>$request->phone, 'country'=>$request->country, 'state'=>$request->state,
'purpose'=>$request->purpose, 'package'=>$request->package, 'months'=>'$months', 'quantity'=>$request->quantity, 'amount'=>$request->amount, 'expiry_date'=>'$expiry_date'];
DB::table('users')->where('id',$request->id)->update($data);
return response()->json($data);
}
Anyone please suggest me a answer. I do changes in my code but It gives this message "message": "SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '$expiry_date' for column addspy.users.expiry_date at row 1 (SQL: update users set id = 47, name = Ayush, phone = 6393611129, country = India, state = UP, purpose = parent, package = basic, months = $months, quantity = 1, amount = 4000, expiry_date = $expiry_date where id = 47)",
"exception": "Illuminate\Database\QueryException",
Thanks in advance

You're sending strings to the database ('$months' & '$expiry_date'). Simply removing the quotes should fix your problem.
i.e.
$data = [
'id' => $request->id,
'name' => $request->name,
'phone' => $request->phone,
'country' => $request->country,
'state' => $request->state,
'purpose' => $request->purpose,
'package' => $request->package,
'months' => $months,
'quantity' => $request->quantity,
'amount' => $request->amount,
'expiry_date' => $expiry_date,
];

Related

add multiple langue using Astrotomic / laravel-translatable package and laravel

i am new in laravel and use Astrotomic / laravel-translatable package for translation
i have problem when i want to add two langue at same time.
i have name_en,name_ar,discription_an,disriptionar as inputs fields.
i get this error Creating default object from empty value
so how can I solve my problem
this is link of package https://github.com/Astrotomic/laravel-translatable
// start add data
public function store(CategoryRequest $request)
{
// prepare data
$validatedData = array(
'url' => $request->url,
'slug' => $request->slug,
'status' => $request->status,
'last_updated_by' => auth('admin')->user()->id,
'created_by' => auth('admin')->user()->id,
'created' => time(),
);
$translated = array(
'name_en' => $request->name_en,
'name_ar' => $request->name_ar,
'description_en' => $request->description_en,
'description_ar' => $request->description_ar,
);
//start define categoru is sub or main
$request ->sub ==1 ? $validatedData['parent_id'] = $request ->category_id: $validatedData['parent_id']=null;
// start update data
DB::beginTransaction();
$add = Category::create($validatedData);
$id = $add->id;
// strat update category report
$categoryReport = CategoryReport::create(
['status' =>$validatedData['status'],
'category_id' =>$id,
'created_by' =>$validatedData['created_by']
,'last_updated_by' =>$validatedData['last_updated_by']]);
$add->translate('ar')->name = $translated['name_ar'];
$add->translate('en')->name = $translated['name_en'];
$add->translate('ar')->description = $translated['description_ar'];
$add->translate('en')->description =$translated['description_en'];
$add ->save();
DB::commit();
return redirect()->back()->with('success','تم اضافه البيانات بنجاح');
}

Method not allowed exception while updating a record

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpExceptionNomessage
I'm getting this error while trying to update a record in the database. Don't know what's the problem. This question might be a duplicate but I've checked all and couldn't find the answer. Please Help me with this.
Controller Update Method:
public function updateEvent(Request $request, $id=''){
$name = $request->name;
$startdate = date_create($request->start_date);
$start_date = $startdate;
$time = $request->start_time;
$start_time = $time;//date("G:i", strtotime($time));
$endDate = date_create($request->end_date);
$end_date =$endDate;
$time_e = $request->end_time;
$end_time = $time_e;//date("G:i", strtotime($time_e));
$location = $request->location;
$description = $request->description;
$calendar_type = $request->calendar_type;
$timezone = $request->timezone;
if ($request->has('isFullDay')) {
$isFullDay = 1;
}else{
$isFullDay = 0;
}
DB::table('events')->where('id', $id)->update(
array(
'name' => $name,
'start_date' => $start_date,
'end_date' => $end_date,
'start_time' => $start_time,
'end_time' => $end_time,
'isFullDay' =>$isFullDay,
'description' => $description,
'calendar_type' => $calendar_type,
'timezone' => $timezone,
'location' => $location,
));
// Event Created and saved to the database
//now we will fetch this events id and store its reminder(if set) to the event_reminder table.
if(!empty($id))
{
if (!empty($request->reminder_type && $request->reminder_number && $request->reminder_duration)) {
DB::table('event_reminders')->where('id', $id)->update([
'event_id' => $id,
'type' => $request->reminder_type,
'number'=> $request->reminder_number,
'duration' => $request->reminder_duration
]);
}
}
else{
DB::table('event_reminders')->insert([
'type' => $request->reminder_type,
'number'=> $request->reminder_number,
'duration' => $request->reminder_duration
]);
}
return redirect()->back();
}
Route:
Route::post('/event/update/{id}', 'EventTasksController#updateEvent');
Form attributes :
<form action="/event/update/{{$event->id}}" method="POST">
{{ method_field('PATCH')}}
i'm calling the same update function inside my calendar page and it working fine there. Don't know why it doesn't work here.
Check the routeing method.
Route::patch('/event/update/{id}', 'EventTasksController#updateEvent');
patch should be the method called on route facade.
Change your route to patch:
Route::patch('/event/update/{id}', 'EventTasksController#updateEvent');
For your comment:
You can send the method to the ajax call by something like data-method attribute on the element you click on,take the method and use it in your ajax call. see this question/answer for help. How to get the data-id attribute?

BadMethodCallException Method Illuminate\Database\Query\Builder::input does not exist

Am getting that error when submitting my form data for storing , Below is my approve_request_post function in controller.
public function approve_request_post(Request $request, $request_hash)
{
$request->validate([
'hosp_no' => 'required',
'transport_cost' => 'required',
'days' => 'required|numeric',
'per_diem' => 'required|numeric',
'service_type' => 'required',
'trans_mean' => 'required',
'cost_payable' => 'required|numeric',
'patient_age' => 'required|numeric',
'doctors_name' => 'required',
'appointment_date' => 'required|date',
'comment' => 'required',
]);
// Start transaction
DB::beginTransaction();
$request = ReferralRequestModel::where('request_hash', $request_hash)->firstOrFail();
$remark = new InsurerRemarksModel;
$remark->ir_hash = encrypt($remark->ir_id);
$remark->req_id = $request->request_id;
$remark->insurer_id = Auth::user()->insurers->insurer_id;
$remark->req_id = $request->request_id;
$remark->hosp_no = $request->input('hosp_no');
$remark->service_type = $request->input('service_type');
$remark->transport_cost = $request->input('transport_cost');
$remark->trans_mean = $request->input('trans_mean');
$remark->days = $request->input('days');
$remark->cost_payable = $request->input('cost_payable');
$remark->patient_age = $request->input('patient_age');
$remark->doctors_name = $request->input('doctors_name');
$remark->appointment_date = $request->input('appointment_date');
$remark->approval_date =Carbon::now();
$remark->ir_status = 'approved';
$remark->save();
//approvalrecord
$approval = new ApprovalModel;
$approval->req_id = $request->request_id;
$approval->approver_id = Auth::user()->id;
$approval->category = 'Insurer | Verified By: ';
$approval->status = 'Verified';
$approval->comment = $request->input('comment');
$approval->save();
//email to all medical team
if( !$remark->save() || !$approval->save() )
{
DB::rollback();
return back()->withInput(Input::all())->with('failure', 'Transaction Not Successful. Check the input data');
}
DB::commit();
return redirect('/insurer-view-submitted-requests')->with('success', 'Referral Request Approved Successfully');
}
Replace this line
$referral_model = ReferralRequestModel::where('request_hash', $request_hash)->firstOrFail();
Because you are replacing the $request with a model instance and trying to get the value using $request->input('hosp_no') something like that
$request->input('hosp_no') that method will try to get input method from your ReferralRequestModel
so replace the above line and use $referral_model where you want.
also suggest to use try , catch block for handle exception. because firstOrFail throw Illuminate\Database\Eloquent\ModelNotFoundException exception if data is not found

Avoid duplication in doctor_id field with where clause in laravel 5.4

this is my doctors id
this is my user id
I can't insert anything when I put unique in the validation of doctor_id. When there's no unique it works fine.
I want to avoid duplicate doctor_id where auth::id == 1. Any advice is appreciated.
public function store(Request $request, $id)
{
$auth = Auth::id();
$constraints = [
'doctor_id' => 'required|unique',
'day1' => 'required|max:20',
'day2'=> 'required|max:60',
'day3' => 'required|max:60'
];
$input = [
'users_id' => $auth,
'doctor_id' => $id,
'day1' => $request['day1'],
'day2' => $request['day2'],
'day3' => $request['day3'],
'day4' => $request['day4'],
...
'day27' => $request['day27'],
'status' => '1'
];
$this->validate($request, $constraints);
Itinerary::create($input);
$added = array('added'=> 'Added Doctor to Itinerary Successful!!');
return redirect()->back()->with($added);
Have you tried this? (assuming your table is named itineraries):
'doctor_id' => 'unique:itineraries'
According to Laravel Doc, you should add the table name, and column name if possible:
unique:table,column,except,idColumn

Laravel 4 - Return the id of the current insert

I have the following query
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
return $results;
}
How would i return the id of the row just inserted?
Cheers,
Instead of doing a raw query, why not create a model...
Call it Conversation, or whatever...
And then you can just do....
$result = Conversation::create(array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now ))->id;
Which will return an id...
Or if you're using Laravel 4, you can use the insertGetId method...In Laravel 3 its insert_get_id() I believe
$results = DB::table('pm_conversations')->insertGetId(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
This method requires that the id of the table be auto-incrementing, so watch out for that...
The last method, is that you can just return the last inserted mysql object....
Like so...
$result = DB::connection('mysql')->pdo->lastInsertId();
So if you choose that last road...
It'll go...
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
$theid= DB::connection('mysql')->pdo->lastInsertId();
return $theid;
}
I would personally choose the first method of creating an actual model. That way you can actually have objects of the item in question.
Then instead of creating a model and just save()....you calll YourModel::create() and that will return the id of the latest model creation
You can use DB::getPdo()->lastInsertId().
Using Eloquent you can do:
$new = Conversation();
$new->currentId = $currentId;
$new->toUserId = $toUserId;
$new->ip = Request::getClientIp();
$new->time = $now;
$new->save();
$the_id = $new->id; //the id of created row
The way I made it work was I ran an insert statement, then I returned the inserted row ID (This is from a self-learning project to for invoicing):
WorkOrder::create(array(
'cust_id' => $c_id,
'date' => Input::get('date'),
'invoice' => Input::get('invoice'),
'qty' => Input::get('qty'),
'description' => Input::get('description'),
'unit_price' => Input::get('unit_price'),
'line_total' => Input::get('line_total'),
'notes' => Input::get('notes'),
'total' => Input::get('total')
));
$w_id = WorkOrder::where('cust_id', '=', $c_id)->pluck('w_order_id');
return $w_id;

Resources