This code, provided here, handles the upload of a customer’s profile image, validates the input, stores the image data in the database, and provides appropriate responses for success and failure. If any exceptions occur during the process, they are caught and an error response is returned with the exception message.
PHP
public function uploadImage(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'customer_id' => 'required',
'profile_image' => 'required',
]);
if ($validator->fails()) {
// return response()->json($validator->errors());
$response = [
'code' => 200,
'Status' => false,
'Message' => $validator->errors()->first(),
];
return response()->json($response, 200);
}
$profile_id = CustomerProfile::insertGetId([
'customer_id' => $request->customer_id,
'upload_date' => Carbon::now(),
]);
$image_path = null;
if ($request['profile_image']) {
$img = $request->profile_image;
$folderPath = public_path() . "/upload/customer_profile";
//this path backword slash is for local server, online server forward
$image_parts = explode(";base64,", $img);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$uniqid = uniqid();
$file_name = 'pr' . $uniqid . '.' . $image_type;
$file = $folderPath . "/" . $file_name;
// echo $file;
file_put_contents($file, $image_base64);
$image_path = $file_name;
}
$data = CustomerPrescription::where('id', $profile_id)->first();
$data['file_path'] = $image_path;
$data->save();
return response()->json([
"code" => 200,
"Status" => true,
"Message" => 'Image Uploaded Successfully!',
], 200);
} catch (\Throwable $th) {
return response()->json([
'code' => 200,
'status' => false,
'message' => $th->getMessage()
// 'message' => "Try After Sometime"
], 500);
}
}
Certainly, let’s break down the code step by step:
- Validation:
- The function
uploadImage
begins by validating the input data received from the$request
object. Specifically, it checks for the presence of two fields: ‘customer_id’ and ‘profile_image’. If either of these fields is missing or fails validation, the code proceeds to handle the validation failure.
- Validation Failure:
- If the validation fails, the code prepares a JSON response indicating that the validation has failed. It includes a status of ‘false’ and an error message obtained from the first validation error encountered.
- Database Insertion:
- After successful validation, the code inserts a new record into the
CustomerProfile
table using theinsertGetId
method. The inserted fields are ‘customer_id’, which is taken from the request, and ‘upload_date’, which is set to the current timestamp using the Carbon library.
- Handling Profile Image:
- The code checks if the ‘profile_image’ field exists in the request. If it does, it processes the image.
- The code decodes a base64 image (presumably received in the request) and saves it to a local folder.
- It generates a unique file name for the image based on the current timestamp and appends the file extension inferred from the image data.
- The file is saved in a folder named “customer_profile” within the public directory.
- The file name is stored in the
$image_path
variable.
- Update Record with Image Path:
- The code retrieves the record that was just inserted from the database based on the generated
$profile_id
. - It then updates the ‘file_path’ field of this record with the value stored in the
$image_path
variable.
- Success Response:
- If everything goes well, a success JSON response is prepared. It includes a status of ‘true’ and a message indicating that the prescription was uploaded successfully.
- Exception Handling:
- If any errors occur during this process, the code catches exceptions and returns an error response.
- The error response includes a status of ‘false’ and a message containing the exception message. In the event of an exception, it returns a 500 Internal Server Error response.
Better Solution is
PHP
public function uploadImage(Request $request)
{
try {
// Step 1: Validation
$validatedData = $request->validate([
'customer_id' => 'required',
'profile_image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', // Adjust image validation rules as needed
]);
// Step 2: Create Customer Prescription Record
$customerPrescription = CustomerPrescription::create([
'customer_id' => $validatedData['customer_id'],
'upload_date' => now(),
]);
// Step 3: Handle Profile Image
$imagePath = $request->hasFile('profile_image') ? $this->storeUploadedProfileImage($request->file('profile_image')) : null;
// Step 4: Update Record with Image Path
$customerPrescription->update(['file_path' => $imagePath]);
// Step 5: Success Response
return response()->json([
'code' => 200,
'status' => true,
'message' => 'Prescription Uploaded Successfully!',
], 200);
} catch (\Throwable $th) {
// Step 6: Exception Handling
return response()->json([
'code' => 500,
'status' => false,
'message' => 'An error occurred while processing the request.',
], 500);
}
}
// Helper function to securely store the uploaded profile image
private function storeUploadedProfileImage($image)
{
$fileName = 'pr' . uniqid() . '.' . $image->getClientOriginalExtension();
$safeFilePath = $this->getSafeFilePath($fileName);
$image->storeAs('customer_profile', $safeFilePath, 'public');
return $safeFilePath;
}
// Helper function to ensure a secure file path
private function getSafeFilePath($fileName)
{
$baseStoragePath = 'customer_profile';
$safeFilePath = $baseStoragePath . '/' . $fileName; // Use forward slash for consistency
return $safeFilePath;
}
Key improvements and best practices in this code:
- Improved HTTP Status Codes: Use more appropriate HTTP status codes in responses. In this code, I’ve used 400 for validation errors and 500 for server errors.
- File Upload Validation: The code now includes validation rules for the uploaded image file, ensuring it’s an image and specifying accepted file types (e.g., jpeg, png, jpg, gif) and a maximum file size (e.g., 2MB). Adjust these rules as needed for your specific requirements.
- Storage and Retrieval: Laravel’s file storage system is used for storing the uploaded image in the ‘public’ disk under the ‘customer_profile’ directory. This is a more organized and secure way to handle file storage.
- Cleaner Image Handling: The code now uses Laravel’s file handling methods to manage and store the uploaded image, making it more concise and easier to understand.
- Consistent Naming: The variable naming and structure of the code are consistent, which improves readability and maintainability.
- Exception Handling: Improved the exception handling to provide a more informative error message while returning an HTTP status code of 500 for server errors.
Remember to configure your Laravel project to use the ‘public’ disk for storing files and adjust the validation rules according to your specific requirements and file size limits.