Laravel 5.4 Image validation is not working - php

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'
]);

Related

403 forbidden when i send PHP code into request to Laravel function

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']);
}
}

Undefined variable in Lumen

I am going to send email using gmail smtp in lumen, Everything working fine but one variable is always undefined, Please let me know where i am wrong
Here is my code
<?php
namespace App\Services;
use Illuminate\Support\Facades\Mail;
class MailService
{
public static function send($mail_to = '', $title = '', $content = '') {
Mail::send('mail', ['title' => $title, 'content' => $content], function ($message) {
$message->from('noreply#gmail.com', 'Test Mail');
$message->to($mail_to);
});
}
}
Here is the Controller
public function register(Request $request)
{
$rules = [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:5',
'phone' => 'required|numeric|min:10',
'business_name' => 'required|unique:users',
'business_type' => 'required'
];
$this->validate($request, $rules);
$data = $request->all();
$hashPassword = Hash::make($data['password']);
$data['password'] = $hashPassword;
$data['is_activated'] = 'false';
$pin = mt_rand(1000, 9999);
$token = hash("sha256", $pin);
$data['token'] = $token;
$data['otp'] = $pin;
$user = User::create($data);
if ($user) {
MailService::send($request->input('email'), 'OTP', $pin);
return response()->json(['response' => true, 'message' => 'User registered Successfully', 'token' => $token], 201);
} else {
return response()->json(['response' => false, 'message' => ' Please check your credentials, Try again'], 400);
}
}
Here is the error
{message: "Undefined variable: mail_to", exception: "ErrorException", file: "D:\xampp\htdocs\api\app\Services\MailService.php", line: 12, trace: Array(28)}
exception: "ErrorException"
file: "D:\xampp\htdocs\api\app\Services\MailService.php"
line: 12
message: "Undefined variable: mail_to"
You are missing $mail_to. you need to use it in function then you may use it otherwise you would get an undefined variable error as you're getting it now.
use($mail_to)
Here your code looks like below.
public static function send($mail_to = '', $title = '', $content = '') {
Mail::send('mail', ['title' => $title, 'content' => $content], function ($message) use($mail_to) {
$message->from('noreply#gmail.com', 'Test Mail');
$message->to($mail_to);
});
}

How to get multiple images in laravel api?

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'])

Object of class Illuminate\Validation\Rules\Unique could not be converted to int

I'm trying to use ignore method in laravel to apply validation on updating profile I have use ignore() for this but looks like I have gone somewhere wrong and ended up with this error can you help me out to find this here is my code. Thanks for your insights :)
User Controller
public function editProfile(Request $request) {
$userId=$request->userId;
$phoneNumber=$request->phoneNumber;
if(!$request){
$this->setMeta("422", "Nothing is there for update");
return response()->json($this->setResponse());
}
$validator =Validator::make($request->all(), [
'phoneNumber' => [
'max:10',
Rule::unique('users')->ignore($userId,'userId'),
],
]);
if ($validator->fails()) {
//$response['meta'] = array('code' => "422", 'message' => "Error, please try again");
$errors = $validator->errors();
if ($errors->first('phoneNumber')) {
$message = $errors->first('phoneNumber');
}
$this->setMeta("403", $message);
return response()->json($this->setResponse());
}
$homeTown = $request->homeTown;
$heightInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userHeight) {
$userHeight=$request->userHeight;
$heightSplit = explode("'", $userHeight, 2);
$feet = $heightSplit[0];
$inches = $heightSplit[1];
$inch=($feet *12)+$inches;
$heightInCm=$inch*2.54;
}
$verticalInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userVertical) {
$userVertical=$request->userVertical;
$verticalSplit = explode("'", $userVertical, 2);
$feet = $verticalSplit[0];
$inches = $verticalSplit[1];
$inch = ($feet *12)+$inches;
$verticalInCm = $inch*2.54;
}
$data= array(
'profilePic' => $request->profilePic,
'nickName' => $request->nickName,
'phoneNumber' => $request->phoneNumber,
'userHeight' => $heightInCm,
'userWeight' => $request->userWeight,
'userVertical' => $verticalInCm,
'userSchool' => $request->userSchool,
'homeTown' => $homeTown,
'cityId' => $request->cityId,
);
User::where('userId',$request->userId)->update($data);
}
Check if you specifying the correct key for the unique check. Your code says userId is the primary key to compare the given id with, is this correct? If the key is 'id' by default then you can ignore the parameter.
Rule::unique('users')->ignore($$request->userId),
'phoneNumber' => 'max:10|unique:users,id,'.$request->userId,
well after the hell of time spent I finally got the answer.
public function editProfile(Request $request) {
$userId=$request->userid;
$phoneNumber=$request->phoneNumber;
if(!$request){
$this->setMeta("422", "Nothing is there for update");
return response()->json($this->setResponse());
}
$validator = Validator::make(
array(
'phoneNumber' => $phoneNumber,
),
array(
'phoneNumber' =>'size:10', Rule::unique('users')->ignore($request->userId, 'userId'),
)
);
if ($validator->fails()) {
//$response['meta'] = array('code' => "422", 'message' => "Error, please try again");
$errors = $validator->errors();
if ($errors->first('phoneNumber')) {
$message = $errors->first('phoneNumber');
}
$this->setMeta("403", $message);
return response()->json($this->setResponse());
}
$homeTown = $request->homeTown;
$heightInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userHeight) {
$userHeight=$request->userHeight;
$heightSplit = explode("'", $userHeight, 2);
$feet = $heightSplit[0];
$inches = $heightSplit[1];
$inch=($feet *12)+$inches;
$heightInCm=$inch*2.54;
}
$verticalInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userVertical) {
$userVertical=$request->userVertical;
$verticalSplit = explode("'", $userVertical, 2);
$feet = $verticalSplit[0];
$inches = $verticalSplit[1];
$inch = ($feet *12)+$inches;
$verticalInCm = $inch*2.54;
}
$data= array(
'profilePic' => $request->profilePic,
'nickName' => $request->nickName,
'phoneNumber' => $request->phoneNumber,
'userHeight' => $heightInCm,
'userWeight' => $request->userWeight,
'userVertical' => $verticalInCm,
'userSchool' => $request->userSchool,
'homeTown' => $homeTown,
'cityId' => $request->cityId,
);
User::where('userId',$request->userId)->update($data);
$this->setMeta("200", "Profile Changes have been successfully saved");
$this->setData("userDetails", $data);
return response()->json($this->setResponse());
}

Passing data to queued Mail object in Laravel 4, using Iron.io

I am trying to set up a queued email in Laravel 4 using the Iron.io driver. I would like to pass some details to the email's Subject and From attributes but they seem to not be making it into the queue request and their presence causes the email to not be sent (not sure where to look for a log with errors). However, simply using Mail::Send() works fine.
Here is the code in question:
public function handleFeedbackForm()
{
$data = array(
'name_f' => Input::get('name_f'),
'name_l' => Input::get('name_l'),
'email' => Input::get('email'),
'commentType' => Input::get('commentType'),
'testimonialPublish_answer' => Input::get('testimonialPublish_answer'),
'comment' => Input::get('message')
);
$rules = array(
'name_f' => 'required',
'name_l' => 'required',
'email' => 'required|email',
'message' => 'required'
);
$v = Validator::make(Input::all(), $rules);
if ($v->passes())
{
$emailInfo = array('name_f' => Input::get('name_f'),
'name_l' => Input::get('name_l'),
'email' => Input::get('email'));
Mail::queue('emails.feedback', $data, function($message) use($emailInfo)
{
$recipients = array();
$form = MailType::find(1);
foreach ($form->users as $user)
{
$recipients[] = $user->email;
}
if (count($recipients) == 0)
{
// Nobody for this field, send to webmaster
$recipients[] = 'someone#somewhere.com';
}
$message->to($recipients)
->from($emailInfo['email'])
->subject('Foobar Feedback Form Message - ' . $emailInfo['name_f'] . ' ' . $emailInfo['name_l']);
});
return Redirect::to('contact')->with('feedbackSuccess', true);
}
else
{
return Redirect::to('contact')->with('feedbackError', true);
}
}
Any ideas? Thanks!

Categories