How to validate if user already exists? - php

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()) {

Related

403 Forbidden when post request with unEscape html content in laravel

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();
}

Ethereum Transfer token via smart contract

I am using web3p/ethereum-tx,web3p/web3.php for transfer ERC-1155 token.I attached a image like that image i want transaction method.
My code is below,
$eth->getTransactionCount($from,function($err,$data) use (&$from_addr_nonce){
$from_addr_nonce = gmp_intval($data->value);
});
$from_addr_nonce = Utils::toHex($from_addr_nonce,true);
$web3 = new Web3($binance_url);
$eth = $web3->eth;
$eth->gasPrice(function ($err, $resp) use (&$gasP) {
if ($err !== null) {
throw new \Exception($err->getMessage());
}
$gasP = $resp;
});
$params = [
'nonce' => $from_addr_nonce,
'from' => $from,
'to' => $contractAddress,
'data' => $data
];
// $contract->at($contractAddress)->estimateGas('transfer', $address, $params, function ($err, $gas) use (&$es) {
// if ($err !== null) {
// throw new \Exception($err->getMessage());
// }
// $es = $gas;
// });
$data = "0x".$contract->getData('transfer',$user_wallet->address,1);
//$data = "0x".$contract->mintNFT($from, $nftMint->token_id);
$transaction = new EthTransaction([
'nonce' => $from_addr_nonce,
'from' => $from,
'to' => $contractAddress,
'gas' => $gasP,
'gasPrice' => sprintf('0x%s', $gasP->toHex()),
'gasLimit' => sprintf('0x%s', '895D0'),
'value' => "0x0",
// 'value' =>$amount,
'chainId' => $chain_id,
'data' => $data,
]);
$signedTx = $transaction->sign($privKey);
$txId = '';
// Sending transaction to the blockchain
$contract->eth->sendRawTransaction(sprintf('0x%s', $signedTx), function ($err, $tx) use (&$txId) {
if ($err !== null) {
throw new \Exception($err->getMessage());
}
$txId = $tx;
});
I dont know how to pass tokenid and corresponding quantity.In the getdata function instead of amount i need token id to be pass.

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

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());
}

Categories