How to retrive from other table and input it again into another table in laravel? - html

I want to retrieve some data from 'tbl_karyawan' and input into 'tbl_absen' which is if the NIP exist from 'tbl_karyawan' then parshing some data into 'tbl_absen'. I was create the code, and the data is going well. but i have something trouble with
i want the data input in Nip_kyn be like 'KIP001' not [{"Nip_kyn":"KIP001"}].
this is my Model
public function presensi($data)
{
$isExist = DB::table('tbl_karyawan')
->where('Nip_kyn', $data)->exists();
if ($isExist) {
$namakyn = DB::table('tbl_karyawan')->where($data)->get('Nama_kyn');
$nippppp = DB::table('tbl_karyawan')->where($data)->select('Nip_kyn')->get($data);
$values = array('Nip_kyn' => $nippppp, 'Nama_kyn' => $namakyn, 'Jam_msk' => now(), 'Log_date' => today());
DB::table('tbl_absen')->insert($values);
} else {
echo 'data not available';
}
}
this is my controller
public function get()
{
$day = [
'time_in' => $this->AbsenModel->timeIN(),
'time_out' => $this->AbsenModel->timeOut(),
'break' => $this->AbsenModel->break(),
// absen here
's' => $this->AbsenModel->absensi(),
];
$data = [
'Nip_kyn' => Request()->Nip_kyn,
];
$this->AbsenModel->presensi($data);
return view('v_absen', $data, $day);
}

Yup, I finally got it, the problem is on my model.
$nama_karyawan = DB::table('tbl_karyawan')->where($data)->value('Nama_kyn');
$nipkyn = DB::table('tbl_karyawan')->where($data)->value('Nip_kyn');
I just change 'get' to 'value'.

Related

How to make update data of mysql in laravel

I'm trying to make an update with values from a form and pass it into an update controller using a route, there's no error given but why there's nothing happen after I updated the data?
Form:
<form action="/update" id="frm_edit" method="post" enctype="multipart/form-data">
Routes:
Route::post('/update', 'EditManga#update'); //update route
Route::post('/admin_page/manga_list', 'Add_Manga_Controller#upload')->name('upload.image');
Route::get('/admin_page/manga_list','ShowData#Manga_list');
Controller:
public function update(Request $request){
$this->validate($request, [
'image' => 'required|image|mimes:jpg,png,jpeg'
]);
//MENGAMBIL FILE IMAGE DARI FORM
$kode_manga = $request->input('kdmanga');
$judul = $request->input('jdmanga');
$alternatif = $request->input('almanga');
$author = $request->input('aumanga');
$status = $request->status;
$lastup = $request->input('lumanga');
$genre = $request->input('grmanga');
$lastc = $request->input('lcmanga');
$sinopsis = $request->input('sinopsis');
$file = $request->file('image');
DB::table('add_manga')->where('kode_manga',$kode_manga)->update([
'judul_manga' => $judul,
'alt_title' => $alternatif,
'author' => $author,
'status' => $status,
'uploaded' => $lastup,
'genre' => $genre,
'latest' => $lastc,
'summary' => $sinopsis
]);
return redirect('/admin_page/manga_list');
}
}
is there any other way or there something's wrong with my code?, Thank you.
In you scenario this another of doing this:
public function update(Request $request, $id)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpg,png,jpeg'
]);
//MENGAMBIL FILE IMAGE DARI FORM
$kode_manga = $request->input('kdmanga');
//getting the target row to updae
$addmanga = DB::table('add_manga')->select('*')
->where('kode_manga',$kode_manga)->get();
$id = $addmanga->id; // getting the id of the target
$add_manga = App\YOUR_MODEL_NAME::find($id);
$add_manga->judul_manga = $request->input('jdmanga');
$add_manga->alt_title = $request->input('almanga');
$add_manga->author = $request->input('aumanga');
$add_manga->status = $request->status;
$add_manga->uploaded = $request->input('lumanga');
$add_manga->genre = $request->input('grmanga');
$add_manga->latest = $request->input('lcmanga');
$add_manga->summary = $request->input('sinopsis');
$add_manga->file = $request->file('image');
$add_manga->save();
return redirect('/admin_page/manga_list');
}
Hope this will work for you!

Api Response and Json laravel format

I'm using Laravel 5.7. and GuzzleHttp 6.0 to get API response
from endpoint
I'm passing query data from Blade form to this function.
public static function prhmulti($multisearch, $start ,$end)
{ $city = $multisearch['city'];
$client = new Client([
'base_uri' => 'https://avoindata.prh.fi/tr/',
'query' => [
'totalResults' => 'true',
'maxResults' => '1000',
'registeredOffice'=> $city,
'companyForm'=>'OY',
'companyRegistrationFrom'=>$start,
'companyRegistrationTo'=>$end,
],
'defaults'=>[
'timeout' => 2.0,
'cookies' => true,
'headers' => [
'content-type' => 'application/json',
'User-Agent' =>"GuzzleHttp/Laravel-App-5.7, Copyright MikroMike"
]]]);
$res = $client->request('GET','v1');
$ResData = json_decode($res->getBody()->getContents());
dd ($ResData) gives all data from API response.
But I am not able to return JSON back to other function
return $this->multisave($ResData);
public static function multisave (data $ResData)
This will parse JSON and
{
foreach ($data->results as $company) {
$name = $company->name;
$Addr = $company->addresses;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
foreach ($company->addresses as $Addr) {
$city = $Addr->city;
$postcode = $Addr->postCode;
$street = $Addr->street;
}
}
save data to Mysql.
$NewCompany = new Company();
$NewCompany = Company::updateOrCreate($array,[
[ 'vat_id', $businessId],
[ 'name', $name],
[ 'form',$companyForm],
[ 'street', $Addr],
[ 'postcode', $postcode],
[ 'city', $city],
[ 'regdate', $registrationDate],
]);
}
IF Parse part and Save part is inside same function code works ok(save only one company),
but I need to separate them because later on it's easier to maintain.
Error which I am getting to return $ResData
" Using $this when not in object context"
Information is in JSON array.
Also foreach part save ONLY one company ?
foreach ($data->results as $company) {
$name = $company->name;
$Addr = $company->addresses;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
foreach ($company->addresses as $Addr) {
$city = $Addr->city;
$postcode = $Addr->postCode;
$street = $Addr->street;
}
So : 1) What is best way to create own function for parse JSON
and other for save data to DB?
2) As foreach loop save only one company data, What is
best way to fix it?
Thanks MikroMike.
Resolved my own question for saving companies to db
First get total number inside Array
use for-loop to make counting
use foreach-loop extract information per single company as object.
$data = json_decode($res->getBody()->getContents());
$total = $data->totalResults;
for ($i = 0; $i < $total; $i++){
$NewCompany = new Company();
foreach ($data->results as $company)
{
$name = $company->name;
$businessId = $company->businessId;
$companyForm = $company->companyForm;
$registrationDate = $company->registrationDate;
$array = [];
Arr::set($array, 'vat_id', $businessId);
Arr::set($array, 'name', $name );
Arr::set($array, 'form', $companyForm);
Arr::set($array, 'regdate', $registrationDate);
$NewCompany = Company::updateOrCreate($array,[
[ 'vat_id', $businessId],
[ 'name', $name],
[ 'form',$companyForm],
[ 'regdate', $registrationDate],
]);
}// END OF MAIN FOREACH
}// END OF For loop
}// END OF FUCNTION
} // END OF CLASS

Using Model to validata data based on hours in cakephp

I am new to cakephp.Below the number being bold is the time the data is being created and code to validate .My problem is to validate the data should between 8 hours not more that using Model. is there any wrong in my code?
sample data=L02A-180129-1215-A
The code to find the table based on data
public function sa01() {
$trv_no = $this->data[$this->alias]['TRV_No_01'];
$line_no = intval(substr($trv_no, 1, 2));
$table_name = 'Ticket_L' . $line_no;
$this->Ticket->setSource($table_name);
$this->Ticket->recursive =-1;
code for validation
Batch_time is a column name for the table
$time = $this->Ticket->find('all',array('conditions' => array('Ticket.Batch_Time >=' => date('Y-m-d H:i:s', strtotime('-8 hour')))));
if(empty($time))
{
$table_name = 'Ticket_L0';
$this->Ticket->setSource($table_name);
//$ticket = $this->Ticket->find('first', array('conditions' => array('Ticket.TRV_No' => $trv_no)));
$time = $this->Ticket->find('all',array('conditions' => array('Ticket.Batch_Time >=' => date('Y-m-d H:i:s', strtotime('-8 hour')))));
if(empty($time)) { return false; } else { return true; }
}
else
{ return true; }
}

Yii2 REST do sorting when response JSON

When the JSON format is response, the original sorting of the data is lost. When response in XML, the sort is saved. How can I preserve the original sorting with JSON?
My controller:
use yii\rest\ActiveController;
class DomainController extends ActiveController
{
...
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['corsFilter' ] = [
'class' => \yii\filters\Cors::className(),
];
$behaviors['contentNegotiator'] = [
'class' => \yii\filters\ContentNegotiator::className(),
'formats' => [
'application/json' => \yii\web\Response::FORMAT_JSON,
],
];
return $behaviors;
}
And action in the controller:
public function actionIndex()
{
$domains = Domain::find()
->leftJoin('WEB_DOMAIN_PRIORITY', 'WEB_DOMAIN_PRIORITY.id = WEB_DOMAIN.priority_id')
->orderBy(['priority' => SORT_DESC])->all();
$test = [];
foreach ($domains as $domain) {
$test[$domain->id] = $domain->title;
}
//echo "<pre>"; print_r($test);die; < -- its ok. right sort
//return $test; < -- its wrong. sort is changed
}
And if i change in behavior this:
'application/json' => \yii\web\Response::FORMAT_JSON,
To:
'application/json' => \yii\web\Response::FORMAT_XML,
I have xml response with right sort.
Only JSON response sorting my array by array keys(ASC).
Here
$test[$domain->id] = $domain->title;
you are adding new array keys. This could change order based on rest/Serializer.
You could apply preserveKeys to serializer as here http://www.yiiframework.com/doc-2.0/yii-rest-serializer.html#$preserveKeys-detail
or don't change keys order.
#Fabrizio Caldarelli not exactly. In this moment response preparing JsonResponseFormatter and it use yii\helpers\Json::encode for format data.

Cakephp 2.61 and comboboxes

Using Cakephp 2.6.1, I have successfully captured and stored single characters in my database using the following code
echo $this->Form->input('grade', array('options' => array( 'G' => 'Good', 'P' => 'Pass','R'=>'Practice Required','F'=>'Fail')));
What I would like to know is how to convert these values back to the display values when retrieving them from the database, ie if the database contains 'P', I want to display 'Pass' in the view and index pages.
I'm certain the answer is simple and straightforward, and sheepishly apologise in advance for my ignorance.
Step-1
Create two new files under Vendor folder.
master-arrays.php
common-functions.php
and Import this two files
Process of import :
Dir : app\Config\bootstrap.php
Add this two lines:
App::import('Vendor', 'common-functions');
App::import('Vendor', 'master-arrays');
Step-2
Now open 'master-arrays.php'
and add this array
function grade_type()
{
$GRADE_TYPE['G'] = 'Good';
$GRADE_TYPE['P'] = 'Pass';
return $GRADE_TYPE;
}
Step-3
Change your view -
echo $this->Form->input('grade', array('options' =>grade_type())));
Step-4
Now add this function in 'common-functions.php'
function id_to_text($id, $arr_master=array()) {
$txt_selected = "";
$id = ''.$id; //Added this as it was creating some warnings online for wrong parameter types
if(is_array($arr_master) && array_key_exists($id,$arr_master)) {
$txt_selected = $arr_master[$id];
} else {
$txt_selected = "";
}
return $txt_selected;
}
Step-5
In Controller or in view
Input:
id_to_text('P',grade_type());
Output:
Pass
Try this,
// In controller
function fun()
{
$grade = array(
'G' => 'Good',
'P' => 'Pass',
'R' => 'Practice Required',
'F' => 'Fail'
);
$this->set('grade', $grade);
if ($this->request->data) {
$key = $this->request->data['Model']['grade'];
$this->request->data['Model']['grade'] = $grade[$key];
$this->Model->save($this->request->data);
}
}
// in view
echo $this->Form->input('grade', array(
'options' => $grade
));
Updated Code
// add in Model
function afterFind($results) {
foreach ($results as $key => $val) {
if (isset($val['MyModel']['status'])) {
$results[$key]['MyModel']['grade_text'] = $this->getGradeText($results[$key]['MyModel']['grade']);
}
}
return $results;
}
public function getGradeText($key)
{
$grades = array(
'G' => 'Good',
'P' => 'Pass',
'R' => 'Practice Required',
'F' => 'Fail'
);
$txt_selected = "";
if(array_key_exists($key,$grades)) {
$txt_selected = $grades[$key];
} else {
$txt_selected = "";
}
return $txt_selected;
}
// in controller
public function index() {
$this->set('data' , $this->paginate('MyModel'));
}
// in view
foreach($data as $value) {
echo $value['MyModel']['grade_text'];
}
I hope it will be help you.