I make service from json but i have problem to show url in json, this url http://git.drieanto.net/LagiDimanaAPI/index.php/user/get_following/1 i try to show url from database but in json show "avatar":"http:\/\/git.drieanto.net\/LagiDimanaAPI\/assets\/image\/avatar\/edwin.png".
how to make to show normal url like this http://git.drieanto.net/LagiDimanaAPI/assets/image/avatar/edwin.png
i used codeigniter this the code
function get_following($id_follower) {
if ($this->muser->cek_following($id_follower) == TRUE) {
$query = $this->muser->get_list_id($id_follower);
$feedback["following"] = array();
foreach ($query->result() as $row) {
$query_list_user = $this->muser->get_all_name_user_from_id($row->id_user);
if ($query_list_user->num_rows() > 0) {
$row_ = $query_list_user->row();
$query_status = $this->muser->get_status($row_->id_user);
$query_status->num_rows();
$row2 = $query_status->row();
$response['status'] = $row2->status;
$response['regid'] = $row_->regid;
$response['id_user'] = $row_->id_user;
$response['email'] = $row_->email;
$response['nama'] = $row_->nama;
$response['jenis_kelamin'] = $row_->jenis_kelamin;
$response['tanggal_lahir'] = $row_->tanggal_lahir;
$response['instansi'] = $row_->instansi;
$response['jabatan'] = $row_->jabatan;
$response['avatar'] = $row_->avatar;
$feedback['success'] = 1;
} else {
$feedback['success'] = 0;
}
array_push($feedback["following"], $response);
}
$feedback['success'] = 1;
echo json_encode($feedback);
} else {
$feedback['success'] = 0;
echo json_encode($feedback);
}
}
thanks
It's just escaping the forwardslashes. You can use str_replace($search_char, $replace_char, $string_to_search), to remove them.
$stuff = json_decode($response);
$url = str_replace("\\", "", $stuff['url']);
It does sound like you're not decoding the JSON because I do believe PHP will unescape all of that stuff for you automatically.
Related
I am getting fewer results than expected , The data returns 57 rows instead of 70 rows. I need help to get all the rows please, I returned a collection using get(), and i joined it with foreach() to include the rows to existing query, Please any help?
public function getempAttendance(Request $request) {
$id = $request->id;
$department_id = $request->department_id;
if($id !== null){ //return based on type;
$emp = AsEmployee::where('id','=',$id)->orderBy('id','ASC')->get();
} else if($department_id != null){
$emp = AsEmployee::where('department_id','=',$department_id)->orderBy('id','ASC')->get();
} else{ //return all if nothing is given;
$emp = AsEmployee::orderBy('id','DESC')->get();
}
foreach($emp as $emp_data){
$department = AsDepartment::where('id','=',$emp_data->department_id)->get(['department'])->first();
if($department !== NULL){
$emp_data->department_name = $department->department;
}else{
$emp_data->department_name = '';
}
$position = AsEmployeePosition::where('id','=',$emp_data->position_id)->get(['position_name'])->first();
if($position !== NULL){
$emp_data->position_name = $position->position_name;
}else{
$emp_data->position_name = '';
}
$attendances = AsAttendanceLog::select('CHECK_IN_TIME','CHECK_OUT_TIME')
->where('EMPLOYEE_ID','=',$emp_data->employee_id)->get();
if($attendances !== NULL){
foreach($attendances as $attendance){
$emp_data->CHECK_IN_TIME = Carbon::parse($attendance->CHECK_IN_TIME)->toTimeString();
$emp_data->CHECK_OUT_TIME = Carbon::parse($attendance->CHECK_OUT_TIME)->toTimeString();
$emp_data->Date = Carbon::parse($attendance->CHECK_IN_TIME)->format('Y-m-d');
$hours = Carbon::parse($attendance->CHECK_OUT_TIME)->diffInSeconds(Carbon::parse($attendance->CHECK_IN_TIME));
$emp_data->Hours = gmdate('H:i', $hours);
}
}else {
$emp_data->CHECK_IN_TIME = '';
$emp_data->CHECK_OUT_TIME = '';
}
}
return $this->sendResponse($emp);
}
Meanwhile, this works but i need the query builder format to allow me use Carbon and do some operations
$attendanceData = DB::table('as_tbl_employee_master AS emp')
->leftJoin('as_tbl_department AS dept','emp.department_id','=', 'dept.id')
->leftJoin('as_tbl_employee_position AS pos', 'emp.position_id', '=', 'pos.id')
->leftJoin('as_tbl_emp_attendance_daily_log AS att', 'att.EMPLOYEE_ID', '=', 'emp.employee_id')
->select('emp.id','emp.employee_id','emp.english_name','dept.department','pos.position_name','att.CHECK_IN_TIME','att.CHECK_OUT_TIME')
->orderby('att.CHECK_IN_TIME', 'DESC')
->get();
return $this->sendResponse($attendanceData);
if the user's table is "one to many" to as_tbl_emp_attendance_daily_log's table.
You should select('as_tbl_emp_attendance_daily_log') first then left join to user's table.
I assumed that you want to show all as_tbl_emp_attendance_daily_log's row. If that right your Query builder should be like this.
$attendanceData = DB::table('as_tbl_emp_attendance_daily_log AS att')
->leftJoin('as_tbl_employee_master AS emp', 'att.EMPLOYEE_ID', '=', 'emp.employee_id')
->leftJoin('as_tbl_department AS dept','emp.department_id','=', 'dept.id')
->leftJoin('as_tbl_employee_position AS pos', 'emp.position_id', '=', 'pos.id')
->select('emp.id','emp.employee_id','emp.english_name','dept.department','pos.position_name','att.CHECK_IN_TIME','att.CHECK_OUT_TIME')
->orderby('att.CHECK_IN_TIME', 'DESC')
->get();
UPDATE
If you want to add the custom attribute to the model you should define it at the model.
This is for reference:
https://laravel.com/docs/5.1/eloquent-serialization#appending-values-to-json
But you can directly change the attribute if you change the collections to the array first.
I don't have your table, so I cannot test it, I just changed it based on your snippet.
public function getempAttendance(Request $request) {
$id = $request->id;
$department_id = $request->department_id;
if($id !== null){ //return based on type;
$emp = AsEmployee::where('id','=',$id)->orderBy('id','ASC')->toArray();
} else if($department_id != null){
$emp = AsEmployee::where('department_id','=',$department_id)->orderBy('id','ASC')->toArray();
} else{ //return all if nothing is given;
$emp = AsEmployee::orderBy('id','DESC')->toArray();
}
for($i=0;$i < count($emp); $i++){
$department = AsDepartment::where('id','=',$emp[$i]->department_id)->get(['department'])->first();
if($department !== NULL){
$emp[$i]['department_name'] = $department->department;
}else{
$emp[$i]['department_name'] = '';
}
$position = AsEmployeePosition::where('id','=',$emp[$i]['position_id'])->get(['position_name'])->first();
if($position !== NULL){
$emp[$i]['position_name'] = $position->position_name;
}else{
$emp[$i]['position_name'] = '';
}
$attendances = AsAttendanceLog::select('CHECK_IN_TIME','CHECK_OUT_TIME')
->where('EMPLOYEE_ID','=',$emp[$i]['employee_id'])->toArray();
$attendances_data = [];
if($attendances !== NULL){
for($j=0;$j<count($attendances);$j++){
$data = [];
$data['CHECK_IN_TIME'] = Carbon::parse($attendance['i']['CHECK_IN_TIME'])->toTimeString();
$data['CHECK_OUT_TIME'] = Carbon::parse($attendance['i']['CHECK_OUT_TIME'])->toTimeString();
$data['Date'] = Carbon::parse($attendance['i']['CHECK_IN_TIME'])->format('Y-m-d');
$hours = Carbon::parse($attendance['i']['CHECK_OUT_TIME'])->diffInSeconds(Carbon::parse($attendance['i']['CHECK_IN_TIME']));
$data['Hours'] = gmdate('H:i', $hours);
$attendances_data[] = $data
}
$emp[$i]['attendances'] = $attendances_data;
}else {
$emp[$i]['attendances'] = [];
$emp[$i]['attendances'] = [];
}
}
return $this->sendResponse($emp);
}
UPDATE
If you want to multiple row, I think you should try this:
$attendanceData = DB::table('as_tbl_emp_attendance_daily_log AS att')
->leftJoin('as_tbl_employee_master AS emp', 'att.EMPLOYEE_ID', '=', 'emp.employee_id')
->leftJoin('as_tbl_department AS dept','emp.department_id','=', 'dept.id')
->leftJoin('as_tbl_employee_position AS pos', 'emp.position_id', '=', 'pos.id')
->select('emp.id','emp.employee_id','emp.english_name','dept.department','pos.position_name','att.CHECK_IN_TIME','att.CHECK_OUT_TIME')
->orderby('att.CHECK_IN_TIME', 'DESC')
->toArray();
for($i=0;$i<count($attendaceData);$i++)
{
$attendaceData[$i]['CUSTOM VARIABLE'] = 'NEW VALUE CUSTOM VARIABLE AT HERE';
}
return $this->sendResponse($emp);
I have created Cake PHP 3, I want to add data, but when I clik submit button, the data is didn't save but the message show data has been save. I add into two different tables. When I try to add data in one table is fine.
This is my controller
StoreController.php
public function add()
{
$this->loadComponent('General');
$setStatus = 1;
$store = $this->Stores->newEntity();
if ($this->request->is('post')) {
// dd( $this->request->getData());exit;
$connection = ConnectionManager::get('ora');
$connection->begin();
$store = $this->Stores->patchEntity($store, $this->request->getData());;
$merchantTable = TableRegistry::get('MasterFile.Merchants');
$merchant = $merchantTable->find()->where(['MERCHANT_CODE'=>$store->MERCHANT_CODE])->first();
$store->MERCHANT_ID = $merchant->MERCHANT_ID;
$store->CREATED_DATE = date("Y-m-d h:i:s");
$store->LAST_UPDATED_DATE = date("Y-m-d h:i:s");
$store->LAST_APPROVED_DATE = date("Y-m-d h:i:s");
$store->LAST_VERSION_DATE = date("Y-m-d h:i:s");
// $store->store_address->LINE1 = $store->LINE1;
// Start - Controller Code to handle file uploading
if(!empty($this->request->data['STORE_LOGO']['name']))
{
$file = $this->request->data['STORE_LOGO']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'png'); //set allowed extensions
$fileName = $this->request->data['STORE_LOGO']['name'];
$uploadPath = WWW_ROOT.'img/store_logo/';
$uploadFile = $uploadPath.$fileName;
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
if(move_uploaded_file($this->request->data['STORE_LOGO']['tmp_name'],$uploadFile))
{
$store['STORE_LOGO'] = $uploadFile;
}
}
}
if(!empty($this->request->data['BACKGROUND_PICTURE']['name']))
{
$fileName = $this->request->data['BACKGROUND_PICTURE']['name'];
$uploadPath = WWW_ROOT.'img/background_picture/';
$uploadFile = $uploadPath.$fileName;
if(move_uploaded_file($this->request->data['BACKGROUND_PICTURE']['tmp_name'],$uploadFile))
{
$store['BACKGROUND_PICTURE'] = $uploadFile;
}
}
// now do the save
if ($this->Stores->save($store)) {
$setStatus = 1;
$message = 'The store has been saved.';
if($setStatus == 1){
$this->loadComponent('General');
$this->loadModel('MasterFile.Addresss');
$setStatus = 1;
$address = $this->Addresss->newEntity();
//dd($this->request->data);
$this->request->data['Address']['LINE1'] = $this->request->data['LINE1'];
$this->request->data['Address']['LINE2'] = $this->request->data['LINE2'];
$this->request->data['Address']['LINE3'] = $this->request->data['LINE3'];
//dd($this->request->data['Address']);
$connection = ConnectionManager::get('ora');
$connection->begin();
$address = $this->Addresss->patchEntity($address, $this->request->data['Address']);
// dd($address);
// now do the save
if ($this->Addresss->save($address)) {
$setStatus = 1;
$message = 'The store has been saved.';
}else{
$setStatus = 0;
$message = 'The store could not be saved. Please, try again.';
}
$this->Flash->set(__($message));
}
}else{
$setStatus = 0;
$message = 'The store could not be saved. Please, try again.';
}
$this->Flash->set(__($message));
if($setStatus){
$connection->commit();
return $this->redirect(['action' => 'index']);
}else {
$connection->rollback();
}
}
$this->set(compact('store'));
$this->set('_serialize', ['store']);
}
What should i do?
Thank you for your help!
Try debugging the entity:
if ($this->Stores->save($store)) {
debug($store);
...
public function actionUpload(){
$model = new CsvForm();
if($model->load(Yii::$app->request->post())){
$file = UploadedFile::getInstance($model,'file');
$filename = 'Data.'.$file->extension;
$upload = $file->saveAs('uploads/'.$filename);
if($upload){
define('CSV_PATH','uploads/');
$csv_file = CSV_PATH . $filename;
$filecsv = file($csv_file);
print_r($filecsv);
foreach($filecsv as $data){
$modelnew = new Customer1();
$hasil = explode(",",$data);
$nim = $hasil[0];
$nama = $hasil[1];
$jurusan = $hasil[2];
$angkatan = $hasil[3];
$modelnew->username = $nim;
$modelnew->firstname = $nama;
$modelnew->lastname = $jurusan;
$modelnew->password = $angkatan;
$modelnew->save();
}
unlink('uploads/'.$filename);
return $this->redirect(['site/index']);
}
}else{
return $this->render('upload',['model'=>$model]);
}
}
This is my CSV data
user1,name,pass,info
user2,name,pass,info
etc..,
So I want to skip Bold content and proceed my execution.
You could shift the array
$filecsvtemp = file($csv_file);
$filecsv = array_shift($filecsvtemp );
in this way the first row of the array is not present in the resulting array
otherwise use a counter
$cnt = 0;
$filecsv = file($csv_file);
print_r($filecsv);
foreach($filecsv as $data){
if ($cnt!=0){
$modelnew = new Customer1();
$hasil = explode(",",$data);
$nim = $hasil[0];
$nama = $hasil[1];
$jurusan = $hasil[2];
$angkatan = $hasil[3];
$modelnew->username = $nim;
$modelnew->firstname = $nama;
$modelnew->lastname = $jurusan;
$modelnew->password = $angkatan;
$modelnew->save();
}
$cnt++;
}
i want to create json like this my json in my api controller in laravel.
here the controller
$data = [];
foreach ($products as $p => $product) {
$components = [];
$product_obj = new StdClass();
$product_obj->id = $product->id;
$product_obj->name = $product->name;
$product_obj->category_id = $product->category_id;
//$product_obj->category_name = $product->category->name;
$product_obj->sku = $product->sku;
$product_obj->weight = $product->weight;
$product_obj->discount_type = $product->discount_type;
$product_obj->additional_price = $product->additional_price;
$product_obj->discount = $product->discount;
$product_obj->start_discount = $date_start;
$product_obj->end_discount = $date_end;
$product_obj->thumbnail = $product->thumbnail;
$product_obj->mime_content_type = $product->mime_content_type;
$product_obj->description = $product->description;
$product_obj->is_active = $product->is_active;
//$product_obj->created_at = $product->created_at;
//$product_obj->updated_at = $product->updated_at;
foreach ($product->components()->get() as $c => $component) {
$item_arr = [];
$component_obj = new StdClass();
$component_obj->id = $component->id;
$component_obj->product_id = $component->product_id;
$component_obj->item_id = $component->item_id;
$component_obj->quantity = $component->quantity;
$component_obj->is_mandatory = $component->is_mandatory;
$component_obj->is_customqty = $component->is_customqty;
//$component_obj->created_at = $component->created_at;
//$component_obj->updated_at = $component->updated_at;
$component_obj->quantity_step = $component->quantity_step;
$component_obj->display_order = $component->display_order;
$component_obj->quantity_display = $component->quantity_display;
$component_obj->default_template = $component->default_template;
foreach ($component->item()->get() as $i => $item) {
$item_option_groups = [];
//$options = [];
$item_templates = [];
$item_backgrounds = [];
$item_background_images = [];
$item_obj = new StdClass();
$item_obj->id = $item->id;
$item_obj->name = $item->name;
$item_obj->price = $item->price;
$item_obj->width = $item->width;
$item_obj->height = $item->height;
$item_obj->allow_image_upload = $item->allow_image_upload;
foreach ($item->itemOptionGroups()->get() as $iog => $item_option_groups) {
$item_option_groups = [];
$item_option_groups_obj = new StdClass();
$item_option_groups_obj->id = $item_option_groups->id;
$item_option_groups_obj->name = $item_option_groups->name;
//miising item option on databse
foreach ($item->options()->get() as $io => $item_options) {
$option = [];
$item_options_obj = new StdClass();
$item_options_obj->id = $item_options->id;
$item_options_obj->item_id = $item_options->item_id;
$item_options_obj->item_group_id = $item_options->item_group_id;
$item_options_obj->option_id = $item_options->option_id;
foreach ($item->option()->get() as $o => $item_options) {
$option_obj = new StdClass();
$option_obj->id = $option->id;
$option_obj->name = $option->name;
$option_obj->price = $option->price;
$option[] = $option_obj;
}
$item_options_obj->option = $item_options->option;
$item_options[] = $item_options_obj;
}
$item_option_groups_obj->item_option_group = $item_option_groups;
$item_option_groups[] = $item_option_groups_obj;
//$component_obj->item = $item_arr;
//$components[] = $component_obj;
}
foreach ($item->itemTemplates()->get() as $it => $item_templates) {
$template = [];
$item_templates_obj = new StdClass();
$item_templates_obj->id = $item_templates->id;
$item_templates_obj->template_id = $item_templates->template_id;
$item_templates_obj->item_id = $item_templates->item_id;
foreach ($item->template()->get() as $t => $template) {
$template_obj = new StdClass();
$template_obj->id = $template->id;
$template_obj->name = $template->name;
$template_obj->row = $template->row;
$template_obj->col = $template->col;
$template_obj->thumbnail = $template->thumbnail;
$template_obj->margin = $template->margin;
$template_obj->padding = $template->padding;
$template[] = $template_obj;
}
$item_templates_obj->template = $template;
$item_templates[] = $item_templates_obj;
}
foreach ($item->itemBackgrounds()->get() as $ib => $item_backgrounds) {
$background_color = [];
$item_backgrounds_obj = new StdClass();
$item_backgrounds_obj->id = $item_backgrounds->id;
$item_backgrounds_obj->item_id = $item_backgrounds->item_id;
$item_backgrounds_obj->background_color_id = $item_backgrounds->background_color_id;
foreach ($item->background_color()->get() as $bc => $background_color) {
$background_color_obj = new StdClass();
$background_color_obj->id = $background_color->id;
$background_color_obj->color = $background_color->color;
$background_color[] = $background_color_obj;
}
$item_backgrounds_obj->background_color = $background_color;
$item_backgrounds[] = $item_backgrounds_obj;
}
foreach ($item->itemBackgroundImages()->get() as $ibi => $item_background_images) {
$background_image = [];
$item_background_images_obj = new StdClass();
$item_background_images_obj->id = $item_background_images->id;
$item_background_images_obj->item_id = $item_background_images->item_id;
$item_background_images_obj->background_image_id = $item_background_images->background_image_id;
foreach ($item->background_image()->get() as $bi => $background_image) {
$background_image_obj = new StdClass();
$background_image_obj->id = $background_image->id;
$background_image_obj->image = $background_image->image;
$background_image[] = $background_image_obj;
}
$item_background_images_obj->background_image = $background_image;
$item_background_images[] = $item_background_images_obj;
}
$item_obj->item_option_groups = $item_option_groups;
//$item_obj->item_option_groups = $options;
$item_obj->item_templates = $item_templates;
$item_obj->item_backgrounds = $item_backgrounds;
$item_obj->item_background_images = $item_background_images;
$item_arr[] = $item_obj;
}
$component_obj->item = $item_arr;
$components[] = $component_obj;
}
$product_obj->product_components = $components;
$data[] = $product_obj;
}
if(count($data) == 1){
$data = $data[0];
}
return response()->json($data);
}
}
and this is what i get from this controller json can anyone solve my this ? looks like the nesting going wrong. please help.
About json responses, you could use Laravel's built-in JSON response for this.
So, instead of building the json fields yourself, let laravel do it for you, like this:
return \Response::json( /* Array||Object to be converted */ );
//or
return response()->json( /* Array||Object to be converted */ );
And about the nested relationships that might not be loaded. Assuming that 'products', and 'items...' are Models:
I think a good way would be to use the 'with' or 'load' methods from your model, like this:
$products->load('components');
If you need multiple nested relationships, you can use the 'dot notation' like described in this question
Hope it helps.
Laravel response function automatically convert an array to JSON.
For example in my controller i have following:
$return_data = array('data' => 'some data','response' => 1);
return response($return_data);
Also The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:
return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);
For more details you can visit: https://laravel.com/docs/5.1/responses#json-responses
i am trying to insert data from the csv excel file to the database but the code seem not to work,
i don't know where am doing wrong.
here is my code:
public function postUploadS(){
$file = array('file' => Input::file('file'));
$rule = array('file' => 'required');
$mime = array( 'text/csv',
'text/plain',
'application/csv',
'text/comma-separated-values',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel'
);
$uploaded_mime = Input::file('file')->getMimeType();
$staff_list=$_FILES['file']['tmp_name'];
$linecount = "";
$cols = 5;
$numx ="";
$mimes = array(
'text/csv',
'application/csv',
'text/comma-separated-values',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel',);
if(empty($staff_list)){
$_SESSION['error']="<font color='#FF0000'>Please choose the csv file to upload</font>";
}
elseif(!in_array($_FILES['file']['type'], $mimes)) {
$_SESSION['error']="<font color='#FF0000'>Invalid file format, Please choose only csv exel format</font>";
}
else{
$staff_list=$_FILES['file']['tmp_name'];
$handle=fopen($staff_list,"r");
// read the first line and ignore it
fgets($handle);
//count number of lines of uploaded csv file
$fh = fopen($staff_list,'rb') or die("ERROR OPENING DATA");
while (fgets($fh) !== false) $linecount++;
fclose($fh);
var_dump($fh); exit();
while(($fileop=fgetcsv($handle,1000,",")) !==false){
$fullname = $fileop[1];
$staff_id = $fileop[0];
$gender = $fileop[2];
$position= $fileop[3];
$department= $fileop[4];
$numx = count($fileop);
$tfulname = trim($fullname);
$lfulname = strtolower($tfulname);
$name_full = explode(' ', $lfulname);
$firstname = $name_full[0];
$middlename = implode(array_slice($name_full, 1, -1));
$lastname = end($name_full);
$phone = '';
$email = '';
$college = '';
if($gender == 'M'){
$gender == 'Male';
}
elseif ($gender =='F') {
$gender == 'Female';
}
DB::beginTransaction();
try{
$staff = new Staff;
$staff->staff_id = $staff_id;
$staff->firstname = $firstname;
$staff->middlename = $middlename;
$staff->lastname = $lastname;
$staff->gender = $gender;
$staff->position = $position;
$staff->phone = $phone;
$staff->email = $email;
$staff->college = $college;
$staff->department = $department;
$staff->save();
}
catch(Exception $e){
Session::put('key','There is a duplicate row in your data,check the file and try again');
}
$cPass = ucfirst($lastname);
$hashed_pass = Hash::make($cPass);
$user = new User;
$user->username = $staff_id;
$user->password = $hashed_pass;
$user->save();
}
if($numx!=$cols){
DB::rollback();
Session::put("error","<font color='#FF0000'>Error,number of columns does not match the defined value,please check your file and try again</font>");
}
elseif(Session::has('key')){
DB::rollback();
Session::put("error","<font color='#FF0000'>Error,duplicate entry detected in your file,please check your file and try again</font>");
}
else{
DB::commit();
Session::put("success","<font color='#0099FF'>Staff list has been uploaded successfully</font>");
}
}
}
when i run above code no data is inserted and i don't get any error. help please
$file = Reader::createFromPath('path-to-your-file');
$result = $file->fetchAll();
foreach($result as $data){
// do database add here
}