I need to send a CSV file through rest api.
I am using reactjs for front end development and constructing backend apis with Laravel.
I am confused with how to send a CSV file through api response ?
Can anyone help me?
this function will download csv file
public function downloadCSV(Request $request){
$table = User::orderBy('created_at','desc')->with('user')->get();
$filename = "users.csv";
$handle = fopen($filename, 'w+');
fputcsv($handle, array('user_name','user_email','country','state','address','zip_code','city'));
foreach($table as $row) {
fputcsv($handle, array(
$row['user_name'],
$row['user_email'],
$row['country'],
$row['state'],
$row['address'],
$row['zip_code'],
$row['city']
));
}
fclose($handle);
$headers = array('Content-Type' => 'text/csv');
return response()->download($filename, 'users.csv', $headers);
}
Related
Error is return in youtube data api call:https://www.googleapis.com/youtube/v3/captions/id
Other api is working with same code for google youtube api's. Any one with past experience with this issue can share his/her experience. Thanks in advance.
try{
$client = new Google_Client();
$client->setApplicationName('My First Project');
$client_id = get_option('gapi_client_id');
$client_secret = get_option('gapi_client_secret');
$redirect_uri = 'https://income.tube/wp-admin/admin.php?page=rnd-eytes';
$simple_api_key = get_option('rnd-eyts');
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($simple_api_key);
$client->setScopes([
'https://www.googleapis.com/auth/youtube.force-ssl',
'https://www.googleapis.com/auth/youtube.readonly',
'https://www.googleapis.com/auth/youtubepartner'
]);
$client->setAccessType('offline');
echo $authCode = get_option('gapi_auth_code');
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAuthConfig($access_token);
// Get the authorized Guzzle HTTP client.
$http = $client->authorize();
$fp = fopen(__DIR__ . '/Libs/YOUR_FILE', 'w');
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$queryParams = [
'tfmt' => 'vtt',
'tlang' => 'fr'
];
$response = $http->request(
'GET',
'/youtube/v3/captions/OdIfTQmbuCS8lIzTWpQoHP66BOQh1VfTCmNAH-qo6vE=',
[
'query' => $queryParams
]
);
echo '<pre>';
print_r($response);
echo '</pre>';
fwrite($fp, $response->getBody()->getContents());
fclose($fp);
}catch(Exception $e){
//catch the exception here
echo '<pre>';
print_r($e);
echo '</pre>';
}
I am trying to make POST to a rest API where I need to send multiple files from a user input form. I have managed to get it to work with a single file, but when there are multiple files sent as an array ($file[]), I can't see anything in the laravel docs to show how this can be done.
$response = 'API_URL';
$response = Http::withToken(ENV('API_KEY'))
->attach('file', fopen($request->file, 'r'))
->post($url, [
'uuid' => $request->uuid,
]);
You can do it by:
->attach('file[0]', fopen($request->file[0], 'r'))
->attach('file[1]', fopen($request->file[1], 'r'))
if your $files is an array of files that wants to send, you can do like below:
$response = Http::withToken(ENV('API_KEY'));
foreach($files as $k => $file)
{
$response = $response->attach('file['.$k.']', $file);
}
$response = $response->post($url, [
'uuid' => $request->uuid,
]);
Attach multiple files if the file name also unknown, together with request data in one request, if request has file or does not have file. with authorization header
if ($method == 'POST') {
// Attached multiple file with the request data
$response = Http::withHeaders($headers);
if($request->files) {
foreach ($request->files as $key=> $file) {
if ($request->hasFile($key)) {
// get Illuminate\Http\UploadedFile instance
$image = $request->file($key);
$fileName = $request->file($key)->getClientOriginalName();
$response = $response->attach($key, $image->get(),$fileName);
}
}
$response = $response->post($this->$requestUrl, $request->all());
} else {
$response = Http::withHeaders($headers)->post($this->webApiBaseUri, $request->all());
}
}
I want to download the data of table in excel file
I have an application in Laravel and I want to add a functionality that download user data in .xls format
Route::get('users/download', function(){
$table = App\User::all();
$filename = "User.csv";
$handle = fopen($filename, 'w+');
fputcsv($handle, array('ID', 'User Name'));
foreach($table as $row) {
fputcsv($handle, array($row['id'], $row['username']));
}
fclose($handle);
$headers = array(
'Content-Type' => 'text/csv'
);
return Response::download($filename, 'User.csv', $headers);
});
This code works fine for .csv files what changes are required for .xls file?
Take a look at Laravel Excel: https://github.com/Maatwebsite/Laravel-Excel
Its very easy to use with Laravel.
I want to update data to the database in ionic. how to make the data update. Here what I tried. I try using postmen to post the api and it appear success but the data does not change.
in api.php
public function update (Request $request)
{
$id = $request->id;
$medname = $request->medname;
$price = $request->price;
$stock = $request->stock;
$medno = $request->medno;
$ingredient = $request->ingredient;
$description = $request->description;
$addinfo = $request->addinfo;
AddMedicine:: where('medname',$medname)->update([
'id' =>$id,
'medname'=>$medname,
'price'=>$price,
'stock'=>$stock,
'medno'=>$medno,
'ingredient'=>$ingredient,
'description'=>$description,
'addinfo'=>$addinfo,
]);
$msg = "Data Updated";
$datamsg = response()->json([
'success' => $msg
]);
return $datamsg->content();
}
route
Route::put('/update','ApiController#update');
Are you sure use PUT request ? Because need to CSRF token please inspect
https://stackoverflow.com/questions/30756682/laravel-x-csrf-token-mismatch-with-postman
I try to send attachement files but i get
Cannot use object of type Illuminate\Http\UploadedFile as array
I use laravel 5.4
Someone know why i'm getting this error ?
( I don't upload the file into a directory, i just want to send the file who was requested on my controller )
Hope someone could help , best regards :)
Here my controller :
public function postSendMassive(Request $request){
$files = $request->file('uploads');
$emails = Structure::where('type_structure_id', 4)->pluck('adresse_email_structure');
$subject = $request->subject;
$bodyMessage = $request->texte;
foreach($files as $file) {
$files[] = [
'file' => $file->getRealPath(),
'options' => [
'mime' => $file->getClientMimeType(),
'as' => $file->getClientOriginalName()
],
];
}
Mail::to('test#gmaIL.com')->send(new MassiveEmail($subject , $bodyMessage , $files));
return back()->with('status', "Email envoyé");
}
here my build mail :
public function build()
{
$subject = $this->subject;
$bodyMessage = $this->bodyMessage;
$files = $this->files;
$email = $this->markdown('email.MassiveMail',compact('bodyMessage'))
->subject($subject.'-'.'FFRXIII Licences & Compétitions');
foreach($this->files as $file) {
$email->attach($file['file'],$file['options']);
}
return $email;
}
This is because $request->file('uploads') returns an object and you're trying iterate over it with foreach
If you want to upload multiple files, make sure you're doing something like this:
<input type="file" name="uploads[]" multiple />
And iterate over uploaded files:
foreach ($request->uploads as $file)
This works!
if($request->hasFile('files')){
foreach ($request->files as $file) {
//get file name with extenstion
$fileNameWithExt = $file->getClientOriginalName();
//get just filename
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//get extension
$extension = $file->getClientOriginalExtension();
//file to store
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
//upload to store
$path = $file->storeAs('${your_storage_path}', $fileNameToStore);
}
}