in laravel if condition not working in controller - laravel

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

Related

Adding data to Database in Laravel along with validated data and non validated data

I have a form in my view and on submit the fields are validated from the controller and I also need to add some data to database which doesn't need any validation. So how can I store these validated data and non validated(non validated data is set in controller it is not submitted along with the form in the view) data in short code.
This is my Controller
public function postRegister($type, Request $request){
$message = "Succesfully Registered, Login to access your Account";
$validatedData = $request->validate([
'name' => 'required|max:100',
'legal_type' => 'required|max:25',
'phonenumber' => 'required|max:12',
'email' => 'required|max:45',
'linkedinprofile' => 'required|max:250',
'address' => 'required:max:350',
'country' => 'required|max:15',
'email' => 'required|max:45',
'password' => 'required|max:120',
'terms' => 'required'
]);
LegalProfessional::create($validatedData);
// $lp = new LegalProfessional();
// $lp->lp_name = $request->input('name');
// $lp->lp_type = $request->input('legal_type');
// $lp->lp_phone = $request->input('phonenumber');
// $lp->lp_email = $request->input('email');
// $lp->lp_linkedin_profile = $request->input('linkedinprofile');
// $lp->lp_address = $request->input('address');
// $lp->country = $request->input('country');
// $lp->lp_membership_type = 'Premium';
// //$lp->lp_rfqs = $request->input('name');
// $lp->lp_username = $request->input('email');
// $lp->password = $request->input('password');
// $lp->save();
Session::flash('message', 'Successfully Registered!');
return redirect('/login');
In PHP you can add associative arrays together with the + operator. This will basicly add you extra fields to the associative array of $validatedData.
LegalProfessional::create(
$validatedData +
[
'lp_membership_type' => 'premium',
]
);
This is in my opinion the easiest and prettiest way to achieve what you want.
Edit
Remove terms, use PHP built in function unset(), that remove items if passed an arrray element.
unset($validatedData['terms']);
LegalProfessional::create(
...
To set a hashed password, just overwrite the $validatedData field.
$validatedData['password'] = Hash::make($request->input('password'));
LegalProfessional::create(
...

Seeking to understand how this error "Illuminate\Http\Exceptions\PostTooLargeException" comes about

I've got the following code and it's working just well as expected when uploading images but I noticed when I try to upload a video I get the error Illuminate\Http\Exceptions\PostTooLargeException. I was expecting to get an error on browser "The make field should be an image" just as the other validations are working. Could someone kindly explain what's happening here, shouldn't validation stop immediately the uploaded file is found to be not an image? Is the validation checking for size first and yet that's not what I've provided in validation?
public function store(Request $request)
{
$this->validate($request, [
'condition' => 'required',
'make' => 'required | alpha',
'model' => 'required | alpha_dash',
'filenames' => 'required | image',
'filenames.*' => 'image',
]);
$files = [];
if($request->hasfile('filenames'))
{
foreach($request->file('filenames') as $file)
{
$name = time().rand(1,100).'.'.$file->extension();
$file->move(public_path('files'), $name);
$files[] = $name;
}
}
$vehicle = new Vehicle;
$vehicle->condition = $request->condition;
$vehicle->make = $request->make;
$vehicle->model = $request->model;
$vehicle->filenames= $files;
$vehicle->save();
return redirect(route('vehicles.create'))->with('flash', 'Vehicle Post Created
Successfully');}

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

Update profile function

I have a function that check updates the users profile info. Currently, if I put |unique:users in the validator every time I try to update the profile info on the form it will not let me because a user (which is me) has my email. So I figured out the unique means that nobody, including the current user can have the email that is being updated.
So I need to compare the current auth email to the one in the database. If it matches then it is ok to update the profile info. I know this is simple but I am not sure how to implement it and if that is the right logic.
So where in this code would I post if (Auth::user()->email == $email){..update email...} http://laravel.io/bin/GylBV#6 Also, is that the right way to do this?
public function editProfileFormSubmit()
{
$msg = 'Successfully Updated';
$user_id = Auth::id();
$user = User::find($user_id);
$first_name = Input::get('first_name');
$last_name = Input::get('last_name');
$email = Input::get('email');
$phone_number = Input::get('phone_number');
$validator = Validator::make(Input::all(), array(
'email' => 'required|email',
'first_name' => 'required',
'last_name' => 'required',
'phone_number' => 'required'
));
if ($validator->fails()) {
return Redirect::route('edit-profile')
->withErrors($validator)
->withInput();
}else{
if(Input::hasFile('picture')){
$picture = Input::file('picture');
$type = $picture->getClientMimeType();
$full_image = Auth::id().'.'.$picture->getClientOriginalExtension();
if($type == 'image/png' || $type == 'image/jpg' || $type == 'image/jpeg'){
$upload_success = $picture->move(base_path().'/images/persons/',
$full_image);
if($upload_success) {
$user->picture = $full_image;
} else {
$msg = 'Failed to upload picture.';
}
}else{
$msg = 'Incorrect image format.';
}
}
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->email = $email;
$user->phone_number = $phone_number;
$user->save();
return Redirect::route('invite')->with('global', $msg);
}
}
Worry not, Laravel has already considered this potential issue! If you take a look at the docs for the unique validation rule you'll see that it can take some extra parameters. As it happens, you can give it an id to ignore when looking at the unique constraint. So what you need to do is work out the id for the current model to update and pass that in. In the case of updating a logged-in user's profile it's made easy by Auth::id() as you already have in your code.
$rules = [
'email' => ['required', 'email', 'unique:users,email,'.Auth::id()],
'first_name' => ['required'],
// etc...
];
Obviously I chose to use the array syntax for validation rules there, but you can do the same with the pip syntax too. In a less specific system (create-or-add in a crud postSave type action) you can still do it by simply dong something like $model = Post::find($id) and then if $model is null you're creating and you just use 'unique' whereas if $model is not null, use 'unique:table,field,'.$model->getKey().

Resources