I am trying to change the parameter name from "filename" to "File1". This is the response.
"url" => "https://dev.abc.com?userName=1234&password=1234&cn=3517546&filename="
This my Laravel code. How should I mention it?
public function get_csv(){
$headers = array(
'Content-Type' => 'text/csv'
);
if (!File::exists(public_path()."/files")) {
File::makeDirectory(public_path() . "/files");
}
$newFileName = "alp-test-".rand(3,5).".csv";
$filename = public_path("files"."\\".$newFileName);
// dd($filename);
$handle = fopen($filename, 'w');
$user_CSV[0] = array('3517546', 'AMZ-test'.rand(3,5), 'UPS-Blue', '766369214006', '5170', '06', '', '3', '1', 'Hanes', '', '3931 Stone Lane', '', 'West Chester', 'PA', '19382');
foreach ($user_CSV as $line) {
fputcsv($handle, $line, ',');
}
fclose($handle);
$getFile = response()->file($filename, $headers);
$response = Http::withBasicAuth('webdev', 'alpdev')
->attach('File1', $getFile)
->post('https://dev.abc.com',
[
'userName' => '1234',
'password' => '1234',
'cn' => '3517546'
]);
return $response;
}
Related
I just want to save my image or file in the database as a URL that can easily get for the frontend. I tried it a lot but did not get a solution if anyone can get me out with this?
public function addPPQuestion(Request $pp_questions)
{
$validate = Validator::make($pp_questions->all(), [
'qual_cat_id' => 'required|exists:qualification_categories,qual_cat_id',
'year_id' => 'required|exists:years,year_id',
'course_id' => 'required|exists:courses,course_id',
'board_id' => 'required|exists:board_of__edus,board_id',
'paper' => 'required|mimes:pdf|max:2048',
]);
if ($validate->fails()) {
$messages = $validate->errors()->count() > 1 ? $validate->errors()->all() : $validate->errors()->first();
return response()->json(['code' => 400, 'message' => $messages], 400);
} else {
$paper = $pp_questions->paper;
$fileName = $paper->getClientOriginalName();
$pp_question = pp_question_answer::create([
'paper' => $pp_questions->paper->storeAs('', $fileName, ''),
'qual_cat_id' => $pp_questions->input('qual_cat_id'),
'year_id' => $pp_questions->input('year_id'),
'course_id' => $pp_questions->input('course_id'),
'board_id' => $pp_questions->input('board_id'),
]);
return response()->json(['code' => 201, 'message' => 'Question Created Successfully',
'object' => $pp_question], 201);
}
}
Step 1: Validate the files as you want in the api.
Content-Type: application/json
It will return JSON data as result.
$request->validate(['file' => 'required|mimes:jpeg,jpg,png,gif,svg,pdf,txt,doc,docx,application/octet-stream,audio/mpeg,mpga,mp3,wav|max:204800']);
Step 2: Make a file name & store it in the folder and get the URL of it.
$unique_id = strtolower(str_replace('.', '', uniqid('', true)) . time());
$photoFile = $request->file('paper');
$extension = $photoFile->getClientOriginalExtension();
$fileNameToStore = $unique_id . '.' . $extension;
$filepath = $photoFile->storeAs('photos', $fileNameToStore);
$pp_question = Model::create([
'paper' => $filepath,
'qual_cat_id' => $pp_questions->input('qual_cat_id'),
'year_id' => $pp_questions->input('year_id'),
'course_id' => $pp_questions->input('course_id'),
'board_id' => $pp_questions->input('board_id'),
]);
return response()->json([
'code' => 201,
'message' => 'Question Created Successfully',
'object' => $pp_question
], 201);
Step 3: To display data on the front-end side.
$imagePath = !empty($pp_question->pdf) && Storage::exists($pp_question->pdf) ? Storage::url($pp_question->pdf) : asset(Storage::url('default/pdf.png');
I want to make an report API with the option of being able to do multiple inputs for violators data, crime scene photo data and personnel data.
I've tried to code like below, but still can't do multiple input. What is the correct way to create multiple inputs in laravel API (with file upload) ?
Controller
public function store(ReportRequest $request)
{
try {
$report = Report::create([
'category_id' => $request->category_id,
'user_id' => Auth::user()->id,
'title' => $request->title,
'description' => $request->description,
'incident_date' => $request->incident_date,
'injured_victims' => $request->injured_victims,
'survivors' => $request->survivors,
'dead_victims' => $request->dead_victims,
'location' => $request->location,
'latitude' => $request->latitude,
'longitude' => $request->longitude
]);
if ($request->category_id !== 4 && $request->violator_photo) {
$violators = $request->file('violator_photo');
$violators = [];
foreach($violators as $key => $value) {
if($request->hasFile('violator_photo')) {
$violator_photo = $request->hasFile('violator_photo');
$fileName = time().'_'.$violator_photo[$key]->getClientOriginalName();
$filePath = $violator_photo[$key]->storeAs('images/pelanggar', $fileName, 'public');
}
$data = new Violator();
$data->report_id = $report->id;
$data->name = $request->violator_name[$key];
$data->photo = $filePath[$key];
$data->age = $request->violator_age[$key];
$data->phone = $request->violator_phone[$key];
$data->save();
}
}
$files = $request->file('crime_scene_photo');
$files = [];
foreach($files as $key => $value) {
if($request->hasFile('crime_scene_photo')) {
$crime_scene_photo = $request->hasFile('crime_scene_photo');
$name = time().'_'.$crime_scene_photo[$key]->getClientOriginalName();
$path = $crime_scene_photo[$key]->storeAs('images/tkp', $name, 'public');
}
$data = new CrimeScenePhoto();
$data->report_id = $report->id;
$data->path = $path[$key];
$data->caption = $request->caption[$key];
$data->save();
}
if (\Auth::user()->unit_id == 2 && $request->personel) {
foreach ($request->personel as $key => $value) {
$report->members()->sync($request->personel[$key]);
}
}
return response()->json([
'status' => '200',
'message' => 'success',
'data' => [
$report,
$request->all()
],
]);
} catch (\Exception$err) {
return $this->respondInternalError([$err->getMessage(), $request->all()]);
}
}
And here is how I tested in postman.
Solved. i changed my code to like this and it work.
public function store(ReportRequest $request)
{
try {
$report = Report::create([
'category_id' => $request->category_id,
'user_id' => Auth::user()->id,
'title' => $request->title,
'description' => $request->description,
'incident_date' => $request->incident_date,
'injured_victims' => $request->injured_victims,
'survivors' => $request->survivors,
'dead_victims' => $request->dead_victims,
'location' => $request->location,
'latitude' => $request->latitude,
'longitude' => $request->longitude
]);
if ($request->hasFile('violator_photo')) {
foreach($request->file('violator_photo') as $key => $value) {
$vio_photo = $request->file('crime_scene_photo');
$fileName = time().'_'.$vio_photo[$key]->getClientOriginalName();
$filePath = $vio_photo[$key]->storeAs('images/pelanggar', $fileName, 'public');
Violator::create([
'report_id' => $report->id,
'name' => $request->violator_name[$key] ?? null,
'photo' => $filePath ?? null,
'age' => $request->violator_age[$key] ?? null,
'phone' => $request->violator_phone[$key] ?? null
]);
}
}
if ($request->hasFile('crime_scene_photo')) {
foreach($request->file('crime_scene_photo') as $key => $value) {
$crime_scene_photo = $request->file('crime_scene_photo');
$name = time().'_'.$crime_scene_photo[$key]->getClientOriginalName();
$path = $crime_scene_photo[$key]->storeAs('images/tkp', $name, 'public');
CrimeScenePhoto::create([
'report_id' => $report->id,
'path' => $path ?? null,
'caption' => $request->caption[$key] ?? null
]);
}
}
if (\Auth::user()->unit_id == 2 && $request->personel_id) {
foreach ($request->personel_id as $key => $value) {
$report->members()->attach($request->personel_id[$key]);
}
}
return response()->json([
'status' => '200',
'message' => 'success',
'data' => [
$report, $report->members, $report->violators, $report->photos
],
]);
} catch (\Exception$err) {
return $this->respondInternalError([$err->getMessage(), $request->all()]);
}
}
I am having 2 methods. In one of the method I am making a call to database, a pure and simple one Document::findOrFail($data->id). But this is always returning me null although a record is already persisted. Any idea how to get this simple thing sorted?
public function lockExport(Request $request){
$document = Document::create([
'user_id' => $this->userId(),
'extension' => $extension,
'name' => $filename,
'file_path' => $filepath,
'size' => File::size($filepath . $filename),
'received_at' => Carbon::now()->format('Y-m-d')
]);
$isAttachment = false;
Cache::put($token, ['file' => $document->file_path . $document->name . '.' . $document->extension, 'is_attachment' => $isAttachment, 'id' => $document->id], 3);
return $this->downloadlockExport($token);
}
public function downloadlockExport($token)
{
try {
$data = (object) Cache::get($token);
// dd I get the full $data as object
$document = Document::findOrFail($data->id);
// undefined. Above query did not execute.
// Thus, below query failed
$document->update(['downloads' => $document->downloads + 1]);
$content = Crypt::decrypt(File::get($data->file));
return response()->make($content, 200, array(
'Content-Disposition' => 'attachment; filename="' . basename($data->file) . '"'
));
} catch (\Exception $e) {
\App::abort(404);
}
}
What you probably would like to do is:
public function lockExport(Request $request){
$document = Document::create([
'user_id' => $this->userId(),
'extension' => $extension,
'name' => $filename,
'file_path' => $filepath,
'size' => File::size($filepath . $filename),
'received_at' => Carbon::now()->format('Y-m-d')
]);
$isAttachment = false;
$token = 'mytoken';
Cache::put($token, ['file' => $document->file_path . $document->name . '.' . $document->extension, 'is_attachment' => $isAttachment, 'id' => $document->id], 3);
return $this->downloadlockExport($token);
}
This way you will get your $token in your called function and you will get the $data correctly as I see.
And in the downloadlockExport() function you will have the ID like this:
$document = Document::findOrFail($data->mytoken['id']);
or you can use:
$document = Document::findOrFail($data->$token['id']);
similar with getting the File value:
$content = Crypt::decrypt(File::get($data->$token['file']));
I have this code I have written and tested. The first phase
mokkle_test(Request $request)
is working. I have issue with how to pass the result of the request to the second phase
First phase:
public function mokkle_test(Request $request)
{
$telco_match=['name'=>'Icell'];
$telco=Telco::where($telco_match)->first();
try{
$client = new Client();
$response = $client->request(
'POST', $telco->send_call, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->cpPwd,
'text' =>$request->text,
'correlator' =>$request->correlator,
'serviceid' =>$request->serviceid,
'shortcode' => $request->shortcode
],
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
$noti=new Notification_log();
$noti->error_message= (string)$response->getBody();
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
return $result;
}catch(\Exception $e)
{
return $e->getMessage();
}
}
... and its working very well.
How do I pass the result of the response into another function shown below.
Second phase:
function subscribe($request,$telco)
{
try{
$client = new Client();
$response = $client->request(
'POST', $telco->billing_callback_2, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->password,
'amount' =>$request->amount,
'shortcode' => $request->shortcode
],
'headers' => [
'auth' => $telco->authorization,
'key' => $telco->key,
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
$amount = $request->amount;
$shortcode = $request->shortcode;
$noti=new Notification_log();
$noti->error_message=(string)$response;
$noti->msisdn=$request->msisdn;
$noti->product_id=$request->productid;
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
$request = array();
$request->text= "Weldone";
$request->amount = $amount;
$request->serviceid="100010";
$request->correlator="876543ghj";
$result_sms=self::mokkle_test($request);
return $result;
}catch(\Exception $e)
{
return $e;
}
}
I tried this, but nothing is happening
$result_sms=self::mokkle_test($request);
Kindly assist. How do I achieve my goal. Kindly assist me.
Here you can pass it to the other method
public function mokkle_test(Request $request)
{
$telco_match = ['name' => 'Icell'];
$telco = Telco::where($telco_match)->first();
try {
$client = new Client();
$response = $client->request(
'POST', $telco->send_call, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->cpPwd,
'text' => $request->text,
'correlator' => $request->correlator,
'serviceid' => $request->serviceid,
'shortcode' => $request->shortcode
],
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
// Here you can pass it to the other method
this.subscribe($response, $telco); // <--- $response will be your "$request" parameter
$noti = new Notification_log();
$noti->error_message = (string)$response->getBody();
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
return $result;
} catch (\Exception $e) {
return $e->getMessage();
}
}
I just noticed yesterday, there was a problem with my reCAPTCHA, last year was fine.
Here's my code:
public function message(Request $request) {
$response = $_POST["g-recaptcha-response"];
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => '6LcwXi8UAAAAAE9zNCVfqwDOIWNazNgdK-0wQv9L',
'response' => $_POST["g-recaptcha-response"]
);
//For debug purpose (remove comments)
//dd($request->all());
$options = array(
'http' => array (
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);
if ($captcha_success->success==false) {
return redirect('/')->with('success', 'You are a bot! Go away!');;
} else if ($captcha_success->success==true) {
$content = array (
'http' => array (
'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($query)."\r\n".
"User-Agent:MyAgent/1.0\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
When I submitted contact form, it gave me this error:
ErrorException in PagesController.php line 37:
file_get_contents(): Content-type not specified assuming
application/x-www-form-urlencoded
Line 37 is:
$verify = file_get_contents($url, false, $context);
I've fixed this, here's my code:
private function check_recaptcha($key){
$secret = '6LdMgJIUAAAAAOvJPW8MHjumG2xQNNuRyw-WctqQ';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$key);
$responseData = json_decode($verifyResponse);
return ($responseData->success)? true:false;
}
public function message(Request $request) {
//Validate
$validator = Validator::make($request->all(), [
'name' => 'required',
'subject' => 'required',
'message' => 'required',
'email' => 'required|email',
'g-recaptcha-response' => 'required',
]);
//If validator failed
if ($validator->fails()) {
return redirect('/')
->withErrors($validator)
->withInput();
}
//Declare variable
$name = $request->input("name");
$email = $request->input("email");
$subject = $request->input("subject");
$message = $request->input("message");
$captchaKey = $request->input("g-recaptcha-response");
//Test reCAPTCHA
if (!$this->check_recaptcha($captchaKey)) {//captcha gagal
return redirect('/')->with('success', 'You are a bot! Go away!');
} else{//captcha sukses
$content = [
'name' => $name,
'email' => $email,
'subject' => $subject,
'message' => $message
];
In my case this header was missing and worked try this
$options = array('http' => array(
'method' => 'POST',
'content' => http_build_query($data),
'header' => 'Content-Type: application/x-www-form-urlencoded'
)
);