How to call data from 2 diferent table by id in eloquent? - database

thats the controller
public function hitung($request, $response, $args)
{
$datauser = User::with(['usia','aktivitas'])->find($args['id']);
$tinggi = $datauser['tinggi'];
$berat = $datauser['berat'];
$nama = $datauser['nama'];
$umur = $datauser['umur'];
$aktivitas = $datauser['aktivitaas_id'];
$usia = $datauser['usia_id'];
$nilai = $datauser->aktivitas->nilai;
$energy = $datauser->usia->energy;
$protein = $datauser->usia->protein;
$lemak = $datauser->usia->lemak;
$karbohidrat = $datauser->usia->karbohidrat;
$amb = 655 + (9.6 * $berat) + (1.8 * $tinggi) - (4.7 * $umur);
$amb = round($amb);
$energytotal = $amb * $nilai + $energy;
$energytotal = round($energytotal);
$protein = (15 * $energytotal / 100) + $protein;
$protein = round($protein);
$lemak = (25 * $energytotal / 100) + $lemak;
$lemak = round($lemak);
$karbohidrat = ($energytotal - ($protein + $lemak)) + $karbohidrat;
$karbohidrat= round($karbohidrat);
return $response ->withJson([
'Nama' => $nama,
'total_energy' => $energytotal ,
'Protein'=> $protein,
'lemak'=> $lemak,
'Karbohidrat'=> $karbohidrat,
]);
}
thats the user model:
<?php
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public $timestamps = false;
protected $fillable = ['username', 'password', 'nama', 'tinggi', 'berat', 'umur', 'usia_id', 'aktivitas_id'];
protected $table = "users";
public function usia()
{
return $this->belongsTo('App\Models\Usia');
}
public function aktivitas()
{
return $this->belongsTo('App\Models\Aktivitas');
}
public function forum()
{
return $this->hasMany('App\Models\Forum');
}
}
thats the aktivitas model:
<?php
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class Aktivitas extends Model
{
protected $table = "aktivitas";
public function user()
{
return $this->hasMany('App\Models\User');
}
}
thats the usia model ,
<?php
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class Usia extends Model
{
protected $table = "usia";
public function user()
{
return $this->hasMany('App\Models\User');
}
}
this code is work in local , but when i hosting it , it didnt work , please need help for my exam ...
i think the problem is in this code ,
$datauser = User::with(['usia','aktivitas'])->find($args['id']);
any different way to do it ?

I guess your local is Windows and remote host is Linux
first of all you should know windows file and folder name is not case sensitive and there is no different between Models and models in windows OS
but Linux file and directory name is Case Sensitive
in your codes:
namespace App\models;
and
return $this->hasMany('App\Models\User');
somewhere you use Models and models
you should check directory name and rename it anywhere you write wrong word

Related

insert computed data in table in laravel

I need to store interest_amount which is computed using get_Attribute function however now I need to insert it into table.
I have used static::saving function to compute interest_amount I don't know how to call it using $data in controller
Loan.php
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $fillable = [
'amount',
'interest',
'status',
'duration',
'member_id',
'loan_type_id',
'interest_type_id',
'loan_payment_type_id'
];
protected $appends = 'interest_amount';
public function getInterestAmountAttribute()
{
return ($this->amount)/100 * $this->interest;
}
public function member()
{
return $this->belongsTo(Member::class,'member_id','id');
}
protected static function boot()
{
parent::boot();
static::saving(function($model) {
$model->interest_amount = ($model->amount/100 ) * $model->interest;
});
}
}
LoanController.php
$data['amount'] = $request->amount;
$data['interest'] = $request->interest;
$data['interest_amount'] = $interest_amount;
$data['duration'] = $request->duration;
$data['status']= $request->status;
$data['member_id'] = $request->name;
$data['loan_type_id']= $request->loan_type;
$data['interest_type_id']= $request->interest_type;
$data['loan_payment_type_id']= $request->payment;
if(DB::table('loans')->insert($data)){
return redirect()->route('loan')->with('success','data was successfuly inserted');
}
I initially didn't have interest_amount column but I added it later. I don't know how to call the saving function with the approach I have used in my controller.
Model events will not fire when you use the query builder to insert data into your tables.
You have to use the Model to save the data, something like this:
If your model attributes are mass assignable:
if((new Loan($data))->save()){
return redirect()->route('loan')->with('success','data was successfuly inserted');
}
otherwise:
$loan = new Loan;
$loan->amount = $request->amount;
$loan->interest = $request->interest;
$loan->interest_amount = $interest_amount;
$loan->duration = $request->duration;
$loan->status = $request->status;
$loan->member_id = $request->name;
$loan->loan_type_id = $request->loan_type;
$loan->interest_type_id = $request->interest_type;
$loan->loan_payment_type_id = $request->payment;
if($loan->save()){
return redirect()->route('loan')->with('success','data was successfuly inserted');
}

Mock databases function from drupal 7

I want to create a phpunit test from the following code, but I'm not even sure if it worth it, because the code contains db_update and db_query functions, so, those are database functions and I don't know if it make sense create a test for this, because I don't know if should assume drupal code is working fine.
<?php
namespace Drupal\forum_innovation\Forum;
/**
* Created by PhpStorm.
* User: ldcontreras
* Date: 30/05/18
* Time: 18:26
*/
class ForumCounter implements ForumInterface {
public static function setForumCounter($forum, $uid) {
$counterState = db_update('forum_counter_states')
->fields(array(
'state' => 'read',
))
->condition('uid', $uid)
->condition('tid', $forum)
->execute();
return $counterState;
}
public static function getForumNotification($forum, $uid) {
$unReadNotifications =
db_query('SELECT count(*) as counter
FROM {forum_counter_states} as f WHERE f.uid = :uid AND f.state = :state AND f.tid = :forum',
array(
':uid' => $uid,
':forum' => $forum,
':state' => 'unread'
)
)->fetchAll();
return $unReadNotifications[0]->counter;
}
}
I'm trying to create a test like this, but I need some help and clarification:
<?php
/**
* Created by PhpStorm.
* User: ldcontreras
* Date: 8/06/18
* Time: 10:02
*/
namespace Drupal\forum_innovation\Forum;
class ForumCounterTest extends \PHPUnit_Framework_TestCase {
public function TestSetForumCounter() {
$db_query = $this->getMock('db_update', array('fields', 'condition', 'execute'));
$db_query->expects($this->once())->method('fields')->with($this->equalTo(array(':uid' => 3024));
$db_query->expects($this->once())->method('condition')->with($this->equalTo(array(':uid' => 3024)));
$db_query->expects($this->once())->method('condition')->with($this->equalTo(
array(':tid' => 83))->will(
$this->returnCallback('callback'));
}
}
Thanks!

Codeigniter autocheck db depending on session value

I'm trying to force my app to check every time it loads a model or controller depending on which is my session value.
This is actually running, but just when I get throw this model.
class News_model extends CI_Model {
public function __construct()
{
parent::__construct();
if($this->session->dbname=='db1'){
$this->db=$this->load->database('db1', TRUE);
}
else{
$this->db=$this->load->database('db2', TRUE);
}
}
public function get_news($slug = FALSE)
{
if ($slug === FALSE)
{
$query = $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news', array('slug' => $slug));
return $query->row_array();
}
}
But I do not war to include that __construct code to all my models or controllers.
I've tried to add on my autoload.php
$autoload['model'] = array('General');
Where my General code is something like this.
class General extends CI_Model {
function __construct()
{
parent::__construct();
if($this->session->dbname=='db1'){
$this->db=$this->load->database('db1', TRUE);
}
else{
$this->db=$this->load->database('db2', TRUE);
}
}
}
How can I do it?
You can do it by creating a base model which will be extended by your models that require the database check.
I have simplified the checking and loading code. A simple ternary determines the string to use and stores it in the variable $dbname. That variable is used to load the database, i.e. $this->load->database($dbname);.
I don't believe you need the second argument to load::database() which means you don't need to set $this->db explicitly. If I'm wrong, use
$this->db = $this->load->database($dbname, TRUE);
Below is the "base" model. The prefix of the file name is determined in config.php with the setting $config['subclass_prefix'] = 'MY_'; Adjust your base model's file and class name to match the 'subclass_prefix' you use.
/application/core/MY_Model.php
<?php
class MY_Model extends CI_Model
{
public function __construct()
{
parent::__construct();
$dbname = $this->session->dbname == 'db1' ? 'db1' : 'db2';
$this->load->database($dbname);
}
}
Use the above to create other models like so...
class News_model extends MY_Model
{
public function get_news($slug = FALSE)
{
if ($slug === FALSE)
{
$query = $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news', array('slug' => $slug));
return $query->row_array();
}
}

load external class and member function in Cakephp 3

I'm working on CakePHP 3.2.
I want to import data in bulk from excel file and save them to database. For this I'm using PHPExcel Library.
I have downloaded the library and extracted in vendor directory and thus the filepath to PHPExcel.php is
/vendor/PHPExcel/Classes/PHPExcel.php
and filepath to IOFactory.php is
/vendor/PHPExcel/Classes/PHPExcel/IOFactory.php
I'm including this in my controller like
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
include '../vendor/PHPExcel/Classes/PHPExcel.php';
include '../vendor/PHPExcel/Classes/PHPExcel/IOFactory.php';
/**
* Products Controller
*
* #property \App\Model\Table\ProductsTable $Products
*/
class ProductsController extends AppController
{
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
if ($this->Auth->user()['status'] != 1) {
$this->Auth->deny(['sell']);
}
$this->Auth->allow(['bulkUpload']);
}
public function bulkUpload()
{
$inputFileName = $this->request->data('excel_data');
if ($inputFileName != '') {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName); // line 33
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($inputFileName);
$objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
$highestRow = $objWorksheet->getHighestRow();
for ($row = 2; $row <= $highestRow; ++$row) {
$this->data['Program']['cycle_month'] = $objWorksheet->getCellByColumnAndRow(1, $row)->getValue();
$this->data['Program']['cycle_year'] = $objWorksheet->getCellByColumnAndRow(2, $row)->getValue();
$this->data['Program']['media_partnum'] = $objWorksheet->getCellByColumnAndRow(3, $row)->getValue();
$resultArray[$row-2] = $this->data['Program'];
}
debug($resultArray);
}
}
}
Note : I have never used such plugin and bulk upload that is why I followed code from This Question on StackOverflow
Now, the problem is, When I select a file and upload, it gives error as
Class 'App\Controller\PHPExcel_IOFactory' not found at line 33
I think the problem is with calling PHPExcel_IOFactory class.
PHPExcel_IOFactory class is inside IOFactory.php file
<?php
/** PHPExcel root directory */
if (!defined('PHPEXCEL_ROOT')) {
/**
* #ignore
*/
define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../');
require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
}
class PHPExcel_IOFactory
{
/**
* Search locations
*
* #var array
* #access private
* #static
*/
private static $searchLocations = array(
array( 'type' => 'IWriter', 'path' => 'PHPExcel/Writer/{0}.php', 'class' => 'PHPExcel_Writer_{0}' ),
array( 'type' => 'IReader', 'path' => 'PHPExcel/Reader/{0}.php', 'class' => 'PHPExcel_Reader_{0}' )
);
/**
* Autoresolve classes
*
* #var array
* #access private
* #static
*/
private static $autoResolveClasses = array(
'Excel2007',
'Excel5',
'Excel2003XML',
'OOCalc',
'SYLK',
'Gnumeric',
'HTML',
'CSV',
);
/**
* Private constructor for PHPExcel_IOFactory
*/
private function __construct()
{
}
public static function identify($pFilename)
{
$reader = self::createReaderForFile($pFilename);
$className = get_class($reader);
$classType = explode('_', $className);
unset($reader);
return array_pop($classType);
}
}
I see it's a simple problem of namespaces. Just put a slash before the name class as it is in the global namespace
$inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
You can use composer to load PHPExcel library. It will auto include all classes in your project.
composer require phpoffice/phpexcel
Cheers :)

Decoding JSON array laravel

Hello i am having slight trouble with arrays in my application. I have a table in my database called "contacts" inside that table i have a column "info" of datatype 'TEXT' where i store a json encoded array. This is my function:
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$contact = new Contacts;
$contact->type = $request->type;
$contact->name = str_replace(' ', ' ', $request->type == 'person' ? $request->first_name . ' ' . $request->other_name . ' ' . $request->last_name : $request->description);
$contact->email = $request->email;
$contact->info = json_encode($request->info);
if ($contact->save())
{
return [
'success' => 'Data was saved successfully!'
];
}
}
Now this saves perfectly however the issues is when i retrieving the data from the database it returns that column as a "string" and as such i am unable to access that array from my front-end javascript (i use angular).
I have tried decoding the entire returned result but that did not work, still had the same problem:
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$type = Input::get('type');
$contacts = "";
if (empty($type))
{
$contacts = Contacts::get();
}
elseif ($type == 'persons')
{
$contacts = Contacts::where('type', 'person')->get();
}
elseif ($type == 'companies')
{
$contacts = Contacts::where('type', 'company')->get();
}
return [
'contacts' => json_decode($contacts)
];
}
Use the $casts property on your model:
class Contacts extends Eloquent
{
protected $casts = ['inof' => 'json'];
}
It'll handle all encoding/decoding for you.
$contact->info = $request->info;

Resources