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

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

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','تم اضافه البيانات بنجاح');
}

in laravel if condition not working in controller

i am trying to use if condition in controller ( IF IMAGE NOT UPLOADED it go to ELSE condition Or else go to IF ) but it was not working , it just redirecting registration from page when submitting a form
code
public function Enrollment(Request $request)
{
$this->validate($request, [
'name' => 'required|string|max:255',
'father_name' => 'required|string|max:225',
'address' => 'required|string|max:255',
'card_id' => 'required|string|max:255',
'image' => 'required|image|mimes:jpeg,png,jpg',
]);
if ($request->image != '')
{
$input['name'] = strtoupper ($request['name']);
$input['father_name'] = strtoupper ($request['father_name']);
$input['address'] = strtoupper ($request['address']);
$input['card_id'] = strtoupper ($request['card_id']);
$input['image'] = time().'.'.$request->image->getClientOriginalExtension();
$folder1 = public_path('IMAGE/');
$path1 = $folder1 . $input['image']; // path 1
$request->image->move($folder1, $input['image']); // image saved in first folder
$path2 = public_path('IMAGE/BACKUP_IMAGE/') . $input['image']; // path 2
\File::copy($path1, $path2);
}else{
$input['name'] = strtoupper ($request['name']);
$input['father_name'] = strtoupper ($request['father_name']);
$input['address'] = strtoupper ($request['address']);
$input['card_id'] = strtoupper ($request['card_id']);
}
Card::create($input);
return back()->with('success','Enrolled Successfully.');
}
try this
if($request->hasfile('user_image'))
Nice that you use laravel. At first I will give you some hints to improve your code snippet.
You've written
it just redirecting registration from page when submitting a form
that's correct, because if you submit the form without an image, the validation will say "false".
You can't check an required in this way:
if ($request->image != '') {
because it's required.
Actually your code skips the validation at all, it would be better if you use the following:
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'father_name' => 'required|string|max:225',
'address' => 'required|string|max:255',
'card_id' => 'required|string|max:255',
'image' => 'required|image|mimes:jpeg,png,jpg',
]);
if ($validator->fails()) {
Session::flash('error', $validator->messages()->first());
return redirect()->back()->withInput();
}
If you dump your dd($validator); you will see all opertunities to validate the $request. Your errors you will find here: $validator->errors().
If something went wrong you should redirect back with the
->withInput()
so all data will stay in the form. Also possible with some explanation for the user ->withErrors():
// message information for the user
$messages = $validator->errors();
$messages->add('Your explanation');
// redirect
return redirect()->route('index')->withErrors($messages)->withInput();
Actually I am unsure why you save all $request in $input.
You can check https://laravel.com/docs/5.8/validation#using-rule-objects that for find an great solution for the strtoupper() usement.
Helpful links:
https://laravel.com/docs/5.8/validation
https://laravel.com/docs/5.8/session#flash-data

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?

How to pass array in POST API?

I'm trying to post booking content with array of passengers but it always return invalid argument supplied for foreach(). What seems to be the problem ?
public function postBooking(Request $request)
{
$user = JWTAuth::parseToken()->authenticate();
$booking = Booking::create([
'service_name' => $request->get('service_name'),
'service_package' => $request->get('service_package'),
'travel_date' => $request->get('travel_date'),
'travel_day' => $request->get('travel_day'),
'travel_time' => $request->get('travel_time'),
'remark' => $request->get('remark'),
'booking_name' => $request->get('booking_name'),
'mobile_number' => $request->get('mobile_number'),
'email' => $request->get('email'),
'nationality' => $request->get('nationality'),
'user_id' => $user->user_id,
]);
$passengers = $request['passengers'];
if(is_array($passengers))
{
foreach($passengers as $passenger)
{
$passenger = Passenger::create([
'passenger_name' => $passenger['passenger_name'],
'ic_passport' => $passenger['ic_passport'],
'booking_id' => $booking->booking_id
]);
}
}
$response = (object)[];
$response->booking = $booking->makeHidden('users');
$response->passengers = $passengers;
return response()->json(['data'=>$response, 'status'=>'ok']);
}
var_dump the $passengers, in my opinion ,the way u get the data from $request is wrong, u show use var_dump()or dd() to see the structure of $request and mostly u can solve the problem.

Laravel 4 code organization

I have some questions to Laravel 4 code organization. I am not the best "clean coder" and come from the Java world and sometimes my PHP / Laravel 4 code looks terrible. I post an example here from my controller:
public function postCreate()
{
$input = array(
'title' => Binput::json('title'),
'gender' => Binput::json('gender'),
'first' => Binput::json('first'),
'last' => Binput::json('last'),
'birthdate' => Binput::json('birthdate'),
'birthplace' => Binput::json('birthplace'),
'citizenship' => Binput::json('citizenship'),
'organizationId' => Binput::json('organizationId'),
'typeId' => Binput::json('typeId'),
'email' => Binput::json('email'),
'phone_private' => Binput::json('phone_private'),
'phone_mobile' => Binput::json('phone_mobile'),
'address_street' => Binput::json('address.street'),
'address_postcode' => Binput::json('address.postcode'),
'address_city' => Binput::json('address.city'),
'address_country' => Binput::json('address.country'),
'educations' => Binput::json('educations'),
'selectedLanguages' => Binput::json('selectedLanguages'),
'work' => Binput::json('work'),
);
$rules = array (
'gender' => 'required|max:1',
'first' => 'required|min:2',
'last' => 'required|min:2',
'birthdate' => 'required',
'organizationId' => 'required',
'typeId' => 'required',
'email' => 'required|email',
);
$v = Validator::make($input, $rules);
if ($v->fails() || empty($input['educations']))
{
$data = array("flash" => 'Firstname, Lastname, Birthdate, Email and at least 1 entry in Educations required.');
return Response::json($data, 500);
}
try {
DB::connection()->getPdo()->beginTransaction();
$member = new Member();
$member->title = $input['title'];
$member->gender = $input['gender'];
$member->first = $input['first'];
$member->last = $input['last'];
$member->birthdate = $input['birthdate'];
$member->birthplace = $input['birthplace'];
$member->citizenship = $input['citizenship'];
$work = new Work();
$work->working = $input['work']['working'];
if($input['work']['working'] == 1){
$work->branch = $input['work']['branch'];
$work->company = $input['work']['company'];
}
$work->save();
$member->work()->associate($work);
$member->save();
foreach($input['educations'] as $eduInput){
$edu = new Education();
$edu->degree = $eduInput['degree'];
if(!empty($eduInput['course'])){
$edu->course = $eduInput['course'];
}
$edu->term = $eduInput['term'];
$edu->completion = $eduInput['completion'];
if(!empty($eduInput['faculty'])){
try{
$faculty = Faculty::findOrFail($eduInput['faculty']['id']);
$edu->faculty()->associate($faculty);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
}
if($eduInput['institutionId'] == 0){
// University
try{
$university = University::findOrFail($eduInput['university']['id']);
$edu->university()->associate($university);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
}else{
// Freetext
$edu->institution = $eduInput['institution'];
}
$edu->save();
$member->educations()->save($edu);
}
foreach($input['selectedLanguages'] as $languageInput){
try{
$lang = Language::findOrFail($languageInput['id']);
$member->languages()->attach($lang);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
}
try{
$memberType = MemberType::findOrFail($input['typeId']);
$member->memberType()->associate($memberType);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
try{
$organization = Organization::findOrFail($input['organizationId']);
$member->organizations()->attach($organization);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
$email = new Email();
$email->email = $input['email'];
$email->primary = true;
$member->emails()->save($email);
// If input for phone is empty
$phone = new Phone();
$phone->phone = $input['phone_private'];
$phone->phoneType()->associate(PhoneType::find(PhoneType::PRIVATE_PHONE));
$member->phones()->save($phone);
$phone = new Phone();
$phone->phone = $input['phone_mobile'];
$phone->phoneType()->associate(PhoneType::find(PhoneType::MOBILE_PHONE));
$member->phones()->save($phone);
$address = new Address();
$address->street = $input['address_street'];
$address->postcode = $input['address_postcode'];
$address->city = $input['address_city'];
$address->country = $input['address_country'];
$address->member()->associate($member);
$address->save();
DB::connection()->getPdo()->commit();
}catch (\PDOException $e) {
DB::connection()->getPdo()->rollBack();
return Response::json("Error while writing to database.", 500);
}
$member->load('emails');
$data = array("flash" => 'Member created successfully.');
return Response::json($data, 200);
}
This is an example from my controller.
Is it normal to get all parameters in this way. It takes much of space.
Can I move my database transaction elsewhere and not storing in the controller ?
In general where to store the code that manages logic ? In the controller ? In the
model ?
Your controller actions are just a sort of middleware in the sense that in there you should not put any of your business logic. a few pointers I can provide:
you can get all the json input with Input::json()->all() which returns an array so you can operate it.
Validation rules are another responsibility so it should be abstracted in another class that you call from the controller, it also may be well suited in your models(or entities).
To help you understand how can you use another class inside your controllers you should look for dependency injection in the laravel docs.
if you can get access to this book https://leanpub.com/laravel by Laravel's creator it will help your understanding of code organization and class responsibilities even outside laravel

Resources