I am creating a laravel API for complaints. This code is not saving multiple images in the database and I have to show multiple images in JSON response in an array. I am using array_get but it's not working for me. I have tried many things but it is not saving images in database. I have no idea. I am saving images in other table.
public function Complains(Request $request)
{
$response = array();
try {
$allInputs = Input::all();
$userID = trim($request->input('user_id'));
$cordID = trim($request->input('cord_id'));
$phone = trim($request->input('phone'));
$address = trim($request->input('address'));
$description = trim($request->input('description'));
// $image = array_get($allInputs, 'image');
$validation = Validator::make($allInputs, [
'user_id' => 'required',
'cord_id' => 'required',
'phone' => 'required',
'address' => 'required',
'description' => 'required',
]);
if ($validation->fails()) {
$response = (new CustomResponse())->validatemessage($validation->errors()->first());
} else {
$checkRecord = User::where('id', $userID)->get();
if (count($checkRecord) > 0) {
$complainModel = new Complains();
$complainModel->user_id = $userID;
$complainModel->cord_id = $cordID;
$complainModel->phone_no = $phone;
$complainModel->address = $address;
$complainModel->description = $description;
$saveData = $complainModel->save();
if ($saveData) {
if ($request->file('image')) {
$path = 'images/complain_images/';
// return response()->json(['check', 'In for loop']);
foreach ($request->file('image') as $image) {
$imageName = $this->uploadImage($image, $path);
$ImageSave = new ComplainImages();
$ImageSave->complain_id = $complainModel->id;
$ImageSave->image_url = url($path . $imageName);
$ImageSave->save();
}
}
$jsonobj = array(
'id' => $userID,
'name' => $cordID,
'email' => $phone,
'phone' => $address,
'description' => $description,
);
return Response::json([
'Exception' => "",
'status' => 200,
'error' => false,
'message' => "Complain Registered Successfully",
'data' => $jsonobj
]);
}
}else{
$response = (new CustomResponse())->failResponse('Invalid ID!');
}
}
} catch (\Illuminate\Database\QueryException $ex) {
$response = (new CustomResponse())->queryexception($ex);
}
return $response;
}
public function uploadImage($image, $destinationPath)
{
$name = rand() . '.' . $image->getClientOriginalExtension();
$imageSave = $image->move($destinationPath, $name);
return $name;
}
There is a mistake in looping allImages. To save multiple images try below code
foreach($request->file('image') as $image)
{
$imageName = $this->uploadImage($image, $path);
// other code here
}
Check if you are reaching the loop
return response()->json(['check': 'In for loop'])
Related
403 error when this type data save.
this problem is only Namecheap server
when save then result in this
**but without unEscape HTML content data save successfully **
data seve with unEscape HTML content.
.................. /admin/page/update route point code below
public function update(Request $request)
{
$input = $request->all();
$content = $request->except(['page_code', 'status', '_token']);
$pageCode = $input['page_code'];
$page = Page::where('code', $pageCode)->first();
if ($page->type == 'dynamic') {
$content = [
'section_id' => $input['section_id'] ?? null,
'meta_keywords' => $input['meta_keywords'],
'meta_description' => $input['meta_description'],
'content' => Purifier::clean(htmlspecialchars_decode($input['content'])),
];
$data = [
'title' => $input['title'],
'data' => json_encode($content),
'status' => $input['status'],
];
} else {
$oldData = json_decode($page->data, true);
foreach ($content as $key => $value) {
if (is_file($value)) {
$oldValue = Arr::get($oldData, $key);
$content[$key] = self::imageUploadTrait($value, $oldValue);
} elseif ($key == 'content') {
$content[$key] = Purifier::clean(htmlspecialchars_decode($value));
}
}
$content = array_merge($oldData, $content);
$data = [
'status' => $input['status'] ?? true,
'data' => json_encode($content)
];
}
$page->update($data);
if ($page->type == 'dynamic') Cache::pull('pages');
notify()->success($page->title . ' ' . __(' Updated
Successfully'));
return redirect()->back();
}
I am trying to update users details but anytime i do not select image i get this error message: "Undefined array key 1" i am guessing it because i do not pass a check to see if an image is coming with the request. Or what am i doing wrong, my code is below.
public function update(UserRequest $request, $id)
{
$user = User::find($id);
if($request->profile_image)
{
$exploded = explode(',', $request->profile_image);
$decoded = base64_decode($exploded[1]);
$fileName = Str::slug("{$request->username}"). ".jpg";
$img = Image::make($decoded)->resize(360, 358)->encode('jpg');
$request->merge(['profile_image' => $fileName]);
Storage::disk('public')->put($fileName,(string) $img);
}
$user->update($request->all());
return response()->json([
'user' => $user,
]);
}
I ended up doing this
public function update(UserRequest $request, $id)
{
$user = User::find($id);
if($request->file('profile_image') )
{
$file = $request->profile_image;
$exploded = explode(',', $file);
$decoded = base64_decode($exploded[1]);
$fileName = Str::slug("{$request->username}"). ".jpg";
$img = Image::make($decoded)->resize(360, 358)->encode('jpg');
// $fileName = Str::slug("{$request->title}".'.'.'jpg');
// $img = Image::make($decoded)->resize(265, 200)->encode('jpg');
$request->merge(['profile_image' => $fileName]);
Storage::disk('public')->put($fileName,(string) $img);
}
$user->update([
'name' => $request->name,
'username' => $request->username,
'email' => $request->email,
// 'password' => $request->password,
'profile_image' => $request->profile_image,
'description' => $request->description,
]);
// $user->update($request->all());
return response()->json([
'user' => $user,
]);
}
But i get this error "message": "SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'profile_image' at row 1 (SQL: update `users` set `profile_image` = data:image/jpeg;base64,/9j/4QAC/9sAhAAGBAQ
Any help would be appreciated
I want to validate if it already exists in the DB, so then show an error message. But I am always getting user already exists in both cases. How can I fix it?
Below is my code:
public function add(Request $request)
{
$request_data = $request->all();
$customer_ids = $request_data['ids'];
$campaigns_id = $request_data['campaigns_id'];
$customer_id_array = explode(',', $customer_ids);
$whereIn = $customer_id_array;
$check_customer = Participant::where('id', $campaigns_id)->whereIn('customer_id', $whereIn)->get();
if (!empty($check_customer)) {
return ['code' => 402, 'status' => 'error', 'data' => $check_customer, 'message' => 'Customer Already Exists'];
}
foreach ($customer_id_array as $key => $value) {
$participantObj = new Participant;
$participantObj['customer_id'] = $value;
$participantObj->campaign_id = $campaigns_id;
// $participantObj->pin_number = $this->randomNumber(3).''.$key;
$data = $participantObj;
$data ->save();
}
return['code' => 200, 'status' => 'success'];
}
Change this line
if (!empty($check_customer)) {
to
if ($check_customer->isNotEmpty()) {
i have a problem in my Laravel function , i am creating a forum for web developers and all requests to the function works fine without no problem in any programming language but when i write PHP code in request which i send to the laravel function it's give me 403 forbidden i don't know why ? this happen when the request include
and if i make
return $req->all(); at the top of the function which receive the request i get Error in the request 301 You can try it by yourself here https://mohamedatef-staging.space/ng-websquare/ in the page of New discussion
https://mohamedatef-staging.space/ng-websquare/new-discuss
public function new_discussion(Request $request){
// return $request->all()['images'];
$data_array = $request->all()['dataArray'];
$data = json_decode($data_array, true);
$validator = Validator::make($data, [
'title' => 'required',
'data' => 'required',
'tags' => 'required',
],[
'title.required' => 'missingTitle',
'data.required' => 'missingData',
'tags.required' => 'missingTags',
]);
if($validator->fails()){
return response($validator->messages(), 200);
}
// $images_array = $request->all()['images'];
// return $images_array;
$urls = [];
if(!empty($request->all()['images'])){
$validator2 = Validator::make($request->all(), [
'images' => 'required|array|min:1',
'images.*' => 'image|mimes:jpeg,jpg,png|max:20000',
], [
'images.*image' => 'image_file_error',
'images.*mimes' => 'image_file_error',
'images.*max' => 'image_file_max',
]);
if($validator2->fails()){
return response($validator2->messages(), 200);
}
$images = $request->all()['images'];
foreach ($images as $image) {
$count = 0 ;
$image_name = time() . '.' . $image->getClientOriginalName();
$image->move(public_path('/images/forum'), $image_name);
$image_url = '/images/forum/'.$image_name;
$urls[] = $image_url;
$count++;
}
}
// }
// return response(['urls' => $urls[0]]);
// return response(['owner' => auth('members')->user()->id]);
$forum_slug = preg_replace('~[^\pL\d]+~u', '-', $data['title']);
$forum_slug2 = strtolower($forum_slug);
$forum = new forum ;
$forum->ownerID = auth('members')->user()->id;
$forum->title = $data['title'];
$forum->slug = $forum_slug2;
$forum->content = $data['data'];
$forum->tags = $data['tags'];
if(!empty($urls[0])){
$forum->img1 = $urls[0];
}
if(!empty($urls[1])){
$forum->img2 = $urls[1];
}
if(!empty($urls[2])){
$forum->img3 = $urls[2];
}
$forum->views = 0;
$forum->status = 0;
$forum->comments = 0;
$done = $forum->save();
if($done){
return response(['status' => 'done']);
}
}
I'm kinda stuck here on images validation in laravel. I have to validation the file input must be an image and for that I used the classical way of laravel validation but I don't why it is not working any clue?
User Controller
public function createProfile(Request $request) {
$phoneNumber=$request->phoneNumber;
if (empty($request->except(['userId','token']))){
$data= array(
'nickName' => '',
'profilePic' => '',
'phoneNumber' => '',
'userHeight' => '',
'userWeight' => '',
'userVertical' => '',
'userSchool' => '',
'homeTown' => '',
);
$this->setMeta("200", "Success");
$this->setData("userDetails", $data);
return response()->json($this->setResponse());
}
if($phoneNumber) {
$validationData= array(
'phoneNumber' => $phoneNumber,
);
$validationRules = array(
'phoneNumber' => [
'regex:/^[0-9]+$/',
'min:10',
'max:15',
Rule::unique('users')->ignore($request->userId, 'userId'),
]
);
if($request->has('profilePic')){
$validationData['profilePic'] = $request->profilePic;
$validationRules['profilePic'] = 'image|mimes:jpeg,bmp,png';
}
$validator = Validator::make($validationData,$validationRules);
if ($validator->fails()) {
$errors = $validator->errors();
if ($errors->first('phoneNumber')) {
$message = $errors->first('phoneNumber');
} else if ($errors->first('profilePic')) {
$message = $errors->first('profilePic');
} else {
$message = Constant::MSG_422;
}
$this->setMeta("422", $message);
return response()->json($this->setResponse());
}
}
$homeTown = $request->homeTown;
$filename='';
$profilePic=$request->file('profilePic');
if(!empty($profilePic)) {
$destinationPath = public_path() . '/uploads/users';
$filename = "image_" . Carbon::now()->timestamp . rand(111, 999) . ".jpg";
$profilePic->move($destinationPath, $filename);
}
$user = User::where('userId',$request->userId)->first();
if($request->hasFile('profilePic')){
$user->profilePic = $filename;
}
$user->nickName=$request->nickName;
$user->phoneNumber=$request->phoneNumber;
$user->userHeight=$request->userHeight;
$user->userWeight=$request->userWeight;
$user->userVertical=$request->userVertical;
$user->userSchool=$request->userSchool;
$user->homeTown=$homeTown;
$user->save();
$this->setMeta("200", "Profile Changes have been successfully saved");
$this->setData("userDetails", $user);
return response()->json($this->setResponse());
}
I would assume the reason your validation isn't working is because you adding the rule inside:
if($request->has('profilePic')){
This needs to be $request->hasFile('profilePic').
Hope this helps!
you can use as like this i think it is better.....
if($request->hasFile('profilePic')){
$rules = array(
'profilePic' => 'required | mimes:jpeg,jpg,png',
);
}
$validator = Validator::make($request->all(), $rules);
Just use this for validation. If you have to handle condition then go through step by step debuging.
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5120',
'description' => 'required'
]);