Laravel Loop through Array Value and Update Users - laravel

I have an app I am working on. I am supposed to get some data from the external API. I am comparing the email from the database to the email in the response, so as to be able to update the user associated with a particular email.
Here is my full code
public function checkpaysub(Request $request) {
$userss = User::all()->pluck('email');
//dd($userss);
foreach($userss as $users) {
$email = $users;
//$ref= $request->reference_code;
$url= 'https://api.paystack.co/customer/';
$url .= $email;
//dd($url);
$client = new Client();
$response = $client->request('GET', $url, [
'headers' => [
'Authorization' => 'Bearer '.'##################',
],
]);
$statusCode = $response->getStatusCode();
$body = json_decode($response->getBody()->getContents());
$sub_cus = $body->status;
$sub_status = $body->data->subscriptions[0]->status;
$sub_email = $body->data->email;
$user_exist = User::where('email', $sub_email)->exists();
if(($body->status == 'true') && $user_exist && $sub_status){
$user = User::where('email', $sub_email)->first();
$user->sub_status = $sub_status;
$user->save();
$users = new UserResource(User::where('email', $sub_email)->first());
return response()->json(array(
'user' => $users
));
}
elseif (($body->status == 'true') && $user_exist) {
$user = User::where('email', $sub_email)->first();
$user->sub_status = "inactive";
$user->save();
$users = new UserResource(User::where('email', $sub_email)->first());
return response()->json(array(
'user' => $users
));
}
}
}
}
This only updates one user. I want to loop through the email and update each user based on the email.

because you have return in foreach so it's only going to loop once.
public function checkpaysub(Request $request) {
$userss = User::all()->pluck('email');
$returnedUsers = collect([]);
foreach($userss as $users) {
$email = $users;
$url= 'https://api.paystack.co/customer/';
$url .= $email;
$client = new Client();
$response = $client->request('GET', $url, [
'headers' => [
'Authorization' => 'Bearer '.'##################',
],
]);
$statusCode = $response->getStatusCode();
$body = json_decode($response->getBody()->getContents());
$sub_cus = $body->status;
$sub_status = $body->data->subscriptions[0]->status;
$sub_email = $body->data->email;
$user_exist = User::where('email', $sub_email)->exists();
if(($body->status == 'true') && $user_exist && $sub_status){
$user = User::where('email', $sub_email)->first();
$user->sub_status = $sub_status;
$user->save();
$users = new UserResource(User::where('email', $sub_email)->first());
$returnedUsers->push($users);
}
elseif (($body->status == 'true') && $user_exist) {
$user = User::where('email', $sub_email)->first();
$user->sub_status = "inactive";
$user->save();
$users = new UserResource(User::where('email', $sub_email)->first());
$returnedUsers->push($users);
}
}
return response()->json(array(
'user' => $returnedUsers->all()
));
}

This can be refactored in a big way to be much more simple:
$client = new Client();
$usersWithUpdatedSubscriptions = collect();
User::chunk(100, function ($users) use ($client, $usersWithUpdatedSubscriptions) {
foreach($users as $user) {
$response = $client->request('GET', "https://api.paystack.co/customer/$user->email", [
'headers' => [
'Authorization' => 'Bearer '.'##################',
],
]);
$body = json_decode($response->getBody()->getContents());
if ($body->status == 'true') && $user->email === data_get($body->data, 'email', null)) {
$user->update([
'sub_status' => data_get($body->data->subscriptions, '0.email', null) ?? 'inactive'
]);
$usersWithUpdatedSubscriptions->push(new UserResource($user));
}
}
});
return response()->json(array(
'user' => $usersWithUpdatedSubscriptions->toArray()
));
What we're doing here:
chunking to ensure we free some memory.
moved the client instantiation outside of the loop so we're not wasting resources on re-instantiation.
created a simple array to hold reference to our users that we can push into.
reduced redundant queries
leveraged null coalescing to simplify deterministic sub_status logic
moved the return outside of the loop

Related

Image Update Problem Using Laravel Query Builder

My All Data has been updated successfully but Image not update and old image not remove. I am using Query Builder.
Can anyone tell me what to do?
My Controller are given below
I want to know something new.
public function update(Request $request,$id)
{
$validatedData = $request->validate([
'name' => 'required|max:255',
'title' => 'required',
'details' => 'required',
]);
$data = array();
$data['name'] = $request->name;
$data['title'] = $request->title;
$data['details'] = $request->details;
$data['status'] = $request->status;
$image=$request->photo;
if ($image) {
$image_name = str_random(20);
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$upload_path = 'public/upload/event';
$image_url = $upload_path.$image_full_name;
$success = $image->move($upload_path,$image_full_name);
if ($success) {
$data['photo'] = $image_url;
$img = DB::table('events')->where('id',$id)->first();
$image_path = $img->photo;
$done = unlink($image_path);
$user = DB::table('events')->where('id',$id)->update($data);
if ($user) {
$notification = array(
'messege' => 'Data Updated Successfully',
'alert-type' => 'success'
);
return redirect('admin/event')->with($notification);
}else{
return redirect()->back();
}
}
}else{
return redirect()->back();
}
//return redirect('admin/event')->with($notification);
}

how to send multiple files with one key in laravel using guzzle Http

I can send multiple files and string data with post man like bellow:
but the question is how to send similar request with laravel http ?
what I did is :
public function performMultiPartRequest($requestUrl, $body)
{
$response = Http::withHeaders(['Accept' => 'application/json']);
$data = [];
foreach ($body as $key => $value) {
if (gettype($value) == 'string') // for string data. works well.
array_push($data,[$key, $value]);
else if (gettype($value) == 'array') { // array of files. doesn't work!
foreach ($value as $file) {
$extension = $file->getClientOriginalExtension();
$response->attach($key , fopen($file, 'r'), mt_rand(100,1000).".".$extension);
}
}
else { // one file. works well.
$extension = $value->getClientOriginalExtension();
$response->attach($key, fopen($value, 'r'), 'temp.'.$extension);
}
}
$response = $response->post($this->baseUri.$requestUrl, $body);
return $response;
}
when I try to send some string key value with a file or files with different keys, it's ok, but when I try to send data with multiple file upload (one key) error happens.
the error message is:
A 'contents' key is required with status code 0
unfortunately I didn't find a solution to do the job with Illuminate\Support\Facades\Http yet, but because of time limitation of the project, I used GuzzleHttp\Client instead:
$client = new Client([
"base_uri" => $url,
]);
$data = [];
$data['multipart'] = [];
foreach ($body as $key => $value) {
if (gettype($value) == 'string') {
array_push($data['multipart'], [
'name' => $key,
'contents' => $value
]);
} else if (gettype($value) == 'array') {
foreach ($value as $k => $file) {
if (file_exists($file)) {
$extension = $file->getClientOriginalExtension();
array_push($data['multipart'], [
'name' => $key."[]",
'contents' => fopen($file, 'r'),
'filename' => mt_rand(100, 1000) . "." . $extension
]);
}
}
}
}
$response = $client->request('POST', $requestUrl, $data);
it works fine for my case.
but any solution to laravel Http facade will be appreciated for this problem.

Laravel Mqtt's subscription doesn't end

I receive an Mqtt message from Laravel and try to do some action, but if you subscribe, you only get one message and it takes about a minute to delay.
I referred to this at https://github.com/salmanzafar949/MQTT-Laravel.
Implementing Mqtttt motion was made by creating a separate controller.
My code is
<?php
namespace App\Http\Controllers;
use Salman\Mqtt\MqttClass\Mqtt;
use Illuminate\Http\Request;
class MqttController extends Controller{
public $token = "";
public function SendMsgViaMqtt(Request $request)
{
$mqtt = new Mqtt();
//$client_id = Auth::user()->id;/
$topic = $request->topic;
$token = $request->token;
$message = $request->message;
$output = $mqtt->ConnectAndPublish("test", $message, "");
if ($output === true)
{
if($token == "none" || !$token){
return "End";
}else{
$this->SubscribetoTopic($token);
}
}else{
return "Failed";
}
}
public function SubscribetoTopic($token)
{
$topic = 'test';
$this->token = $token;
$message = [];
$mqtt = new Mqtt();
$client_id = "";
$mqtt->ConnectAndSubscribe($topic, function($topic, $msg){
if($msg == "end"){
$message = [
'title' => '魚が釣れました',
'body' => '釣竿を確認してください',
'click_action' => 'Url'
];
}else if($msg == "no"){
$message = [
'title' => '測定できません',
'body' => '波が強すぎると測れません',
'click_action' => 'Url'
];
}else{
return "end";
}
return $this->sendCrul($this->token, $message);
}, "");
}
public function sendCrul($token, $message){
define('SERVER_API_KEY', 'APIKEY');
$tokens = $token;
$header = [
'Authorization: Key=' . SERVER_API_KEY,
'Content-Type: Application/json'
];
$payload = [
'to' => $tokens,
'notification' => $message
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://fcm.googleapis.com/fcm/send",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode( $payload ),
CURLOPT_HTTPHEADER => $header
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err){
echo "cURL Error #:". $err;
}else{
return $response;
}
// return "ok";
}
}
If you're in trouble like me, let me know how.

Auth user entry in table api

This is friend request code, When i request to another user than token(login user or auth user)didn't entry in table. This is my frd table, you can show here..How can i set auth user as user_id_2 and entry in data table
public function request(Request $request) {
$input =$request->all();
$user = User::find($request->user_id_1);
$friend->user_id_2 = Auth::guard('api')->user()->id;
if(empty($user)){
return [
'status' => 'error',
'msg' => 'no user found'
];
}
if($request->approved == "yes"){
$friend = new Friend();
$friend->user_id_1 = $user->id;
$friend->approved = "yes";
// dd($user);
$friend->save();
$data = array("status" => $user);
return $data;
}
else{
$friend->approved = false;
$friend->save();
return [
'user_id' => $user->id,
'true' => true
];
}
}
Please update your code below.
public function request(Request $request) {
$input =$request->all();
$user = User::find($request->user_id_1);
if(empty($user)){
return [
'status' => 'error',
'msg' => 'no user found'
];
}
if($request->approved == "yes"){
$friend = new Friend();
$friend->user_id_1 = $user->id;
$friend->user_id_2 = Auth::guard('api')->user()->id;
$friend->approved = "yes";
$friend->save();
$data = array("status" => $user);
return $data;
}
else{
$friend->approved = false;
$friend->save();
return [
'user_id' => $user->id,
'true' => true
];
}
}

How to get and validate application/json data in Laravel?

I send data from client to server in application/json content type.
Then I try to take this information in server side like as:
public function register(Request $request)
{
$data = $request->json()->all();
var_dump($data); die();
}
It returns me empty array()
Also I tried to validate incoming POST using this:
$validator = Validator::make($request->json()->all(), []);
How to get and validate application/json data in Laravel?
I get POST data like as:
dd($_POST);
array:1 [▼
"application/json" => "{"id":6,"unique_code":null,"name":"О","secondname":"П","lastname":"Валерьевич","datebirth":"14/10/1991 00:00:00","taxcode":"4545","gender":"1","created_at":null,"file":"C:\\db\\tests\\22-07-2017\\MMM1.TXT","orders":{"profession":"Директор","pacient_id":null,"payment":"1","kind_work":"1,2","factory_name":"FALKO","factory_edrpou":"2020","factory_departament":"IT","status_pass":"1","office_address":"Kiev","unique_code":"0","enterprise_id":"12","status":null},"http_code":null}"
]
I have an api I post json to. I have an api end point where I post this json
{
"email":"youremail#triumworks.com",
"phone": "phone",
"name": "name",
"password": "password"
}
The corresponding controller that handles the request looks like
public function create_account(Request $request){
$data = json_decode(file_get_contents('php://input'));
$response = new Responseobject;
$array_data = (array)$data;
$validator = Validator::make($array_data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
'phone' => 'required|string|min:12|max:12|unique:users',
]);
if($validator->fails()){
$response->status = $response::status_failed;
$response->code = $response::code_failed;
foreach ($validator->errors()->getMessages() as $item) {
array_push($response->messages, $item);
}
}
else{
$api_token = str_random(60);
$user = new User();
$user->api_token = $api_token;
$user->name = $data->name;
$user->email = $data->email;
$user->phone = $data->phone;
$user->password = bcrypt($data->password);
if($user->save()){
$response->status = $response::status_ok;
$response->code = $response::code_ok;
$response->result = $user;
}
}
return Response::json(
$response
);
}
This does the same thing as the one above.
public function create_account(Request $request){
$response = new Responseobject();
$validator = Validator::make($request->json()->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
'phone' => 'required|string|min:12|max:12|unique:users',
]);
if($validator->fails()){
$response->status = $response::status_failed;
$response->code = $response::code_failed;
foreach ($validator->errors()->getMessages() as $item) {
array_push($response->messages, $item);
}
}
else{
$api_token = str_random(60);
$user = new User();
$user->api_token = $api_token;
$user->name = $data->name;
$user->email = $data->email;
$user->phone = $data->phone;
$user->password = bcrypt($data->password);
if($user->save()){
$response->status = $response::status_ok;
$response->code = $response::code_ok;
$response->result = $user;
}
}
return Response::json(
$response
);
}
The posted data will end up in the request body parameter bag. You get the data either via $request->all() or $request->request->all().
So the Validator looks like this:
$validator = Validator::make($request->all(), []);
Dive deeper:
Or you can use the validate() method in your controllers. Which look like this:
$this->validate($request->all(), []);
Read more about this in the Laravel docs.
To make things even more complicator, you don't even need to inject the Request instance to your controller. You can use the request() helper function. The register method then looks like this:
public function register()
{
$this->validate(request()->all(), [
'email' => 'required|email',
'password' => 'required|min:6|confirmed',
]);
}

Resources