I am using manual DB transactions in my controller.
public function exportUsers(){
DB::beginTransaction();
try{
$data = new \App\Models\User();
$excelData = $data->getMemberData();
$reportGeneratedOn = date('dMY');
$report_file_name = 'All_Members_'.$reportGeneratedOn.'.xls';
DB::table('settings')->where('id',1)->update(['user_export_status_id'=>2]);
$excelHTML = view('administrator.member.excel',compact('excelData'))->render();
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Html();
$spreadsheet = $reader->loadFromString($excelHTML);
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$fileName = md5('allmembers_'. microtime()).".xls";
$path = storage_path('app/temp/');
$writer->save( $path . $fileName );
$excel_file_content = file_get_contents( $path . $fileName );
$data = $this->S3Upload($fileName , env('S3_MEMBERS_EXPORT_PATH'), env('S3_MEMBERS_EXPORT_URL'), $excel_file_content,$report_file_name );
if ( $data['status'] ){
DB::table('settings')->where('id',1)->update(['user_export_status_id'=>3]);
DB::table('settings')->where('id',1)->update(['user_export_path'=>$data['preSignedUrl']]);
if( is_file($path . $fileName) ) {
#unlink( $path . $fileName );
}
}
DB::commit();
return response()->json(['error' => 0, 'code' => 200, 'message' => 'Please download the generated excel.','status'=>3, 'report_url' => $data['preSignedUrl']], 200);
}
catch(\Exception $e){
DB::rollBack();
return response()->json(['error' => 1, 'code' => 200, 'message' => 'An error occured while generating the report.'.$e->getMessage().' : '.$e->getFile().'-'.$e->getLine()], 200);
}
}
But using this I got an error like below
Error : An error occured while generating the report.DOMDocument::loadHTML(): htmlParseEntityRef: no name in Entity, line: 2855 :
C:\wamp64\www\O2X\Trunk\Web\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Reader\Html.php-619
My database has a user_export_status_id field which at first has value 1..When an export starts it get updated as 2. But after I got error, it is not roll backed to 1. Dataabse still has value 2.
Related
when I'm trying to update user I got this error
this error point out at $user->first_name = $request->input('first_name');
update method
public function update($id, Request $request){
$this->validate($request, array(
'first_name' => 'string|max:255',
'last_name' => 'string|max:255',
'email' => "string|email|max:255|unique:users,email,$id",
'password' => "sometimes|nullable |string|min:8,$id",
'avatar' => 'image|mimes:jpg,jpeg,gif,png,svg|max:2048',
));
$password = bcrypt(request('password'));
$user = User::where('email',$request['email'])->first();
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
if(!empty($request->password))
{
$user->password = $password;
}
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save( public_path('/images/avatars/' . $filename ) );
$user->avatar = $filename;
}
$user->roles()->detach();
if ($request['user']) {
$user->roles()->attach(Role::where('name','User')->first());
}
if ($request['editor']) {
$user->roles()->attach(Role::where('name','Editor')->first());
}
if ($request['admin']) {
$user->roles()->attach(Role::where('name','Admin')->first());
}
$user->save();
return redirect('admin/users')->with('success', 'user is successfully saved');
}
Your assignment $user is null because there is no record with the email you are providing.
Use findOrFail($request['email']) so that you throw a ModelNotFoundException in this scenario.
OR
$user = User::where('email',$request['email'])->first();
if(!is_null($user) { // check not null of $user here
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
}
References:
https://laravel.com/docs/5.7/eloquent#retrieving-single-models
https://laracasts.com/discuss/channels/laravel/errorexception-in-profilecontrollerphp-line-98-creating-default-object-from-empty-value
You should use FindOrFail method instead
so instead of using this line:
$user = User::where('email',$request['email'])->first();
use this:
$user = User::findOrFail($id);
so FindOrFail will get the user by id and if it does not exist it will fail and show 404 Not found.
I after install
composer require intervention/image
I want to upload image and after submit a form, I get this error.
The file "C:\xampp\tmp\php1D5F.tmp" does not exist
public function store(ArticleRequest $request)
{
auth()->loginUsingId(1);
$imagesUrl = $this->uploadImages($request->file('images'));
$article = auth()->user()->article()->create(array_merge($request->all(), ['images' => $imagesUrl]));
$article->categories()->attach(request('category'));
return redirect(route('articles.index'));
}
protected function uploadImages($file)
{
$year = Carbon::now()->year;
$imagePath = "/upload/images/{$year}/";
$filename = $file->getClientOriginalName();
$file = $file->move(public_path($imagePath) , $filename);
$sizes = ["300" , "600" , "900"];
$url['images'] = $this->resize($file->getRealPath() , $sizes , $imagePath , $filename);
$url['thumb'] = $url['images'][$sizes[0]];
return $url;
}
private function resize($path , $sizes , $imagePath , $filename)
{
$images['original'] = $imagePath . $filename;
foreach ($sizes as $size) {
$images[$size] = $imagePath . "{$size}_" . $filename;
Image::make($path)->resize($size, null, function ($constraint) {
$constraint->aspectRatio();
})->save(public_path($images[$size]));
}
return $images;
}
I tried Change the code:
$imagesUrl = $this->uploadImages($request->file('images'));
return $imagesUrl;
It displaied return $imagesUrl well.
images
300 "/upload/images/2018/300_tvto.jpg"
600 "/upload/images/2018/600_tvto.jpg"
900 "/upload/images/2018/900_tvto.jpg"
original "/upload/images/2018/tvto.jpg"
thumb "/upload/images/2018/300_tvto.jpg"
I think problem from array_merge
So what's the solution?
You need to convert ArticleRequest to Request and bring it to the controller page like below.
public function store(Request $request)
{
$this->validate(request(),[
'title' => 'required|max:250',
'type' => 'required',
'description' => 'required',
'image' => 'required|mimes:jpeg,png,bmp',
'path.*' => 'required|mimes:avi,mp4,.mov,wmv',
'price' => 'required',
]);
I'm trying to upload a file through FileUploadUI::widget in yii2 advanced. But I can't achieve my goal. I don't know what the problem is, but the file doesn't appear in the folder I wish to upload to.
this is my view
<?= FileUploadUI::widget([
'model' => $model,
'attribute' => 'img',
'url' => ['image-upload', 'id' => $model],
'gallery' => false,
'fieldOptions' => [
'accept' => 'image/*'
],
'clientOptions' => [
'maxFileSize' => 2000000
],
// ...
'clientEvents' => [
'fileuploaddone' => 'function(e, data) {
console.log(e);
console.log(data);
}',
'fileuploadfail' => 'function(e, data) {
console.log(e);
console.log(data);
}',
],
]); ?>
this is controller my controller is into backend but I want to upload the file to frontend/web/img/temp action
public function actionImageUpload()
{
$model = new MyNews();
$imageFile = UploadedFile::getInstance($model, 'img');
$directory = Yii::getAlias('/../frontend/web/img/temp/');
if ($imageFile != null) { //can't saveAs() file into my ../img/temp/ folder
$uid = 'qqqq';
$fileName = $uid . '.' . $imageFile->extension;
$filePath = $directory . $fileName;
if ($imageFile->saveAs($filePath)) {
$path = '/../frontend/web/img/temp/' . $fileName;
//.....
}
}
return '';
}
You should use aliases defined by Yii like #frontend #backend rather than providing the path inside the Yii::getAlias(), few common like i stated are defined in common/config/bootstrap.php like
Yii::setAlias ( '#frontend' , dirname ( dirname ( __DIR__ ) ) . '/frontend' );
Yii::setAlias ( '#backend' , dirname ( dirname ( __DIR__ ) ) . '/backend' );
The path you are providing is also wrong because Yii is inside the backend/web/ not at the root of backend app from where you are trying to upload.
What i would suggest is to define your path inside the common/config/bootstrap.php like below
Yii::setAlias('#uploadDir',realpath(Yii::getAlias('#frontend').'/web/img/temp/'));
and then change your code to the following
public function actionImageUpload()
{
$model = new MyNews();
$imageFile = UploadedFile::getInstance($model, 'img');
$directory = Yii::getAlias('#uploadDir');
if ($imageFile != null) { //can't saveAs() file into my ../img/temp/ folder
$uid = 'qqqq';
$fileName = $uid . '.' . $imageFile->extension;
$filePath = $directory . $fileName;
if ($imageFile->saveAs($filePath)) {
Yii::$app->session->setFlash('success','The file has been uploaded successfuly');
return $this->redirect('index');
}
}
}
I am still on the process of learning Yii 2 framework. I was able to create a form that uploads excel file then save to database using phpexcel. I want to enhance it in a way that the data from the uploaded excel will be displayed on a table in view so the user can check the data if they are the same with the excel file. After checking, the user will have two options whether CANCEL or CONTINUE.
Here is my controller method to read file and save:
public function importExcel($model, $readFile, $dir)
{
try {
$readFileType = \PHPExcel_IOFactory::identify($readFile);
$objReader = \PHPExcel_IOFactory::createReader($readFileType);
$objPHPExcel = $objReader->load($readFile);
}
catch(Exception $e) {
die('Error reading data from excel file.');
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
for($row = 9; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray('A'. $row . ':' . $highestCol . $row, NULL, TRUE, FALSE);
$objPHPExcel->getActiveSheet()
->getStyle('A'. $row . ':' . $highestCol . $row)
->getNumberFormat()->setFormatCode('0000');
// ->setFormatCode( \PHPExcel_Style_NumberFormat::FORMAT_TEXT );
if($row == 9) {
continue;
}
$document = new Document();
$document->type_id = ($rowData[0][0] == 'Ordinance' ? 1 : 2);
$document->no = $rowData[0][1];
$document->series = $rowData[0][2];
$document->title = $rowData[0][3];
$document->author = $rowData[0][5];
$document->date_approved = date('Y-m-d', strtotime($rowData[0][8].' '.$rowData[0][9].' '.$rowData[0][10]));
$document->region_c = $model->region_c;
$document->province_c = $model->province_c;
$document->citymun_c = $model->citymun_c;
$document->catParent = 1;
$document->category_id = 1;
$document->file_url = $dir . '/unzip/' . $rowData[0][13];
$document->save();
}
}
I did this and it worked.
try {
$readFileType = \PHPExcel_IOFactory::identify($readFile);
$objReader = \PHPExcel_IOFactory::createReader($readFileType);
$objPHPExcel = $objReader->load($readFile);
}
catch(Exception $e) {
die('Error reading data from excel file.');
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
for($row = 9; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray('A'. $row . ':' . $highestCol . $row, NULL, TRUE, FALSE);
$objPHPExcel->getActiveSheet()
->getStyle('A'. $row . ':' . $highestCol . $row)
->getNumberFormat()->setFormatCode('0000');
if($row == 9) {
continue;
}
$data[] = array(
'type' => $rowData[0][0],
'no' => $rowData[0][1],
'series' => $rowData[0][2],
'title' => $rowData[0][3],
'author' => $rowData[0][5],
'dateapproved' => date('Y-m-d', strtotime($rowData[0][8].' '.$rowData[0][9].' '.$rowData[0][10])),
'file' => $rowData[0][13]
);
}
$dataProvider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('display', [
'dataProvider' => $dataProvider,
]);
}
If your rowData contain the data and is an array of the row read form excel you can do this
$provider = new ArrayDataProvider([
'allModels' => $rowData,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('your:view', [
'provider' => $provider,
]);
and in your grdiView
<?= GridView::widget([
'dataProvider' => $provider,
......
I am having an issue with getting this working with PDO not sure how to do it. I tried but kept getting an error. I will keep trying to figure it out. If anyone can point me in the write direction would be a big help
/** Function to Add Product **/
function add_product() {
$data = json_decode(file_get_contents("php://input"));
$prod_name = $data->prod_name;
$prod_desc = $data->prod_desc;
$prod_price = $data->prod_price;
$prod_quantity = $data->prod_quantity;
print_r($data);
$qry = 'INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) values ("' . $prod_name . '","' . $prod_desc . '",' .$prod_price . ','.$prod_quantity.')';
$qry_res = mysql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
/** Function to Get Product **/
function get_product() {
$qry = mysql_query('SELECT * from product');
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array(
"id" => $rows['id'],
"prod_name" => $rows['prod_name'],
"prod_desc" => $rows['prod_desc'],
"prod_price" => $rows['prod_price'],
"prod_quantity" => $rows['prod_quantity']
);
}
print_r(json_encode($data));
return json_encode($data);
}
what I tried and I get no data inserting
/** Function to Add Product **/
function add_product() {
$data = json_decode(file_get_contents("php://input"));
$prod_name = $data->prod_name;
$prod_desc = $data->prod_desc;
$prod_price = $data->prod_price;
$prod_quantity = $data->prod_quantity;
print_r($data);
$qry = "INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) VALUES (:prod_name,:prod_desc,:prod_price,:prod_quantity)";
$q = $conn->prepare($qry);
$q->execute(array(':prod_name'=>$prod_name,
':prod_desc'=>$prod_desc,
':prod_price'=>$prod_price,
':prod_quantity'=>$prod_quantity,
));
$qry_res = mssql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
db setup
<?php
/****** Database Details *********/
$host = "localhost";
$user = "root";
$pass = "";
$database = "shopping";
$con = mysql_connect($host,$user,$pass);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
mysql_select_db($database,$con);
/*******************************/
?>