Undefined array key "id" in CodeIgniter 4 - php

Undefined array key "id" in CodeIgniter 4
enter image description here
public function update($id)
{
$slug = url_title($this->request->getVar('nama_rak'), '-', true);
$this->rakModel->save([
'id' => $id,
'nama_rak' => $this->request->getVar('nama_rak'),
'slug' => $slug,
'detail_rak' => $this->request->getVar('detail_rak'),
'created_at' => $this->request->getVar('created_at'),
'updated_at' => $this->request->getVar('updated_at')
]);
return redirect()->to('/master/master_rak')->with('pesan', 'Data Berhasil diubah!');
}
this is the construct
class Master extends BaseController
{
protected $rakModel;
public function __construct()
{
$this->rakModel = new RakModel();
}
// Pengadaan Buku
public function master_rak()
{
$data = [
'pages' => 'Master Data',
'title' => 'Data Rak',
'rak' => $this->rakModel->getRak()
];
echo view("master/master_rak", $data);
}

Related

Laravel resource return empty array

I have resource where i get product data trough third table but having hard time make relationships work on models so it return empty array.
Logic
Product has many barcodes
Barcodes can have (belongsTo) damage
In damage we get product trough barcode table (we store barcode_id)
I also included fillable part of each column so you can see columns in database.
Code
Product model
class Product extends Model
{
protected $fillable = [
'name', 'slug', 'stock', 'cover', 'description', 'sku', 'price', 'discount',
];
public function barcodes()
{
return $this->hasMany(Barcode::class);
}
}
Barcode model
class Barcode extends Model
{
protected $fillable = [
'product_id', 'sku', 'serial_number', 'price', 'discount',
];
public function product()
{
return $this->belongsTo(Product::class);
}
public function damages()
{
return $this->hasMany(DamageProduct::class);
}
}
DamageProduct model
class DamageProduct extends Model
{
protected $fillable = [
'outlet_id', 'user_id', 'barcode_id', 'description',
];
public function barcode()
{
return $this->belongsTo(Barcode::class);
}
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
}
DamageProductsResource resource
class DamageProductsResource extends JsonResource
{
public function toArray($request)
{
$arrayData = [
'id' => $this->id,
'outlet' => new OutletsResource($this->whenLoaded('outlet')),
'user' => new usersResource($this->whenLoaded('user')),
'barcode' => new BarcodeResource($this->whenLoaded('barcode')),
'description' => $this->description,
];
return $arrayData;
}
}
Result
Any idea?
Update
In case you need to see how BarcodeResource resource looks like here it is:
public function toArray($request)
{
$arrayNull = [
'id' => $this->id,
'product' => new ProductsResource($this->whenLoaded('product')),
'sku' => $this->sku,
'serial_number' => $this->serial_number ? (Int) $this->serial_number : null,
'price' => (Int) $this->price,
'discount' => $this->discount ? (Int) $this->discount : null,
];
}
I would say you simply forgot the return statement in your BarcodeResource
public function toArray($request)
{
$arrayNull = [
'id' => $this->id,
'product' => new ProductsResource($this->whenLoaded('product')),
'sku' => $this->sku,
'serial_number' => $this->serial_number ? (Int) $this->serial_number : null,
'price' => (Int) $this->price,
'discount' => $this->discount ? (Int) $this->discount : null,
];
return $arrayNull; // this is missing
}

phpunit test in laravel doesn't show the real sesion table

When I use the browser, I see that the values in the session are correct because I use them to display data.
However, when I display a session table in phpunit, it only shows the value for one key:
Controller:
public function add(Book $book)
{
$cart = session('cart');
Book::addToCart($cart, $book);
return back();
}
Model:
public static function addToCart($cart, Book $book)
{
if (!$cart) {
self::createCart($book);
} else {
self::updateCart($cart, $book);
}
}
private static function createCart(Book $book)
{
$cart = [
$book->id => [
'id' => $book->id,
'title' => $book->title,
'quantity' => 1,
'image' => $book->image,
'price' => $book->price
]
];
session(['cart' => $cart]);
}
private static function updateCart($cart, Book $book)
{
if(isset($cart[$book->id])){
$cart[$book->id]['quantity']++;
session(['cart' => $cart]);
} else {
$cart[$book->id] = [
'id' => $book->id,
'title' => $book->title,
'quantity' => 1,
'image' => $book->image,
'price' => $book->price
];
session(['cart' => $cart]);
}
}
for example simple test (result in img)
use WithoutMiddleware;
/** #test */
public function cart_is_created()
{
$book = Book::first();
$this->get('/add-to-cart/' . $book)
->assertSessionHas('cart');
dd(session()->all());
}
Could you show us your tests? When using phpunit with Laravel there's some traits/classes that make sure you connect to a test database instead. This database is usually emptied before testing, which might explain you findings.

An uncaught Exception was encountered, Call to undefined method

I'm having this error and been trying to figure whats wrong for like 3 days straight with no luck:
An uncaught Exception was encountered
Type: Error
Message: Call to undefined method Nsbh::post()
Filename: application\controllers\nsbh.php
Line Number: 25
nsbh.php
<?php
Class Nsbh extends CI_Controller{
var $API ="";
function __construct() {
parent::__construct();
$this->API="http://localhost/rest_ci/index.php";
$this->load->library('session');
$this->load->library('curl');
$this->load->helper('form');
$this->load->helper('url');
}
function index(){
$data['datansbh'] = json_decode($this->curl->simple_get($this->API.'/nsbh'));
$this->load->view('nsbh/list',$data);
}
function create(){
if(isset($_POST['submit'])){
$data = array(
'id' => $this->post('id'),
'name' => $this->post('name'),
'location' => $this->post('location'),
'tgl' => $this->post('tgl'),
'addrs' => $this->post('addrs'));
$insert = $this->curl->simple_post($this->API.'/nsbh', $data, array(CURLOPT_BUFFERSIZE => 10));
if($insert)
{
$this->session->set_flashdata('hasil','Insert Succeed');
}else
{
$this->session->set_flashdata('hasil','Insert Failed');
}
redirect('nsbh');
}else{
$this->load->view('nsbh/create');
}
}
function edit(){
if(isset($_POST['submit'])){
$data = array(
'id' => $this->input->post('id'),
'name' => $this->input->post('name'),
'location' => $this->input->post('location'),
'tgl' => $this->input->post('tgl'),
'addrs' => $this->input->post('addrs'));
$update = $this->curl->simple_put($this->API.'/nsbh', $data, array(CURLOPT_BUFFERSIZE => 10));
if($update)
{
$this->session->set_flashdata('hasil','Update Succeed');
}else
{
$this->session->set_flashdata('hasil','Update Failed');
}
redirect('nsbh');
}else{
$params = array('id'=> $this->uri->segment(3));
$data['datansbh'] = json_decode($this->curl->simple_get($this->API.'/nsbh',$params));
$this->load->view('nsbh/edit',$data);
}
}
function delete($id){
if(empty($id)){
redirect('nsbh');
}else{
$delete = $this->curl->simple_delete($this->API.'/nsbh', array('id'=>$id), array(CURLOPT_BUFFERSIZE => 10));
if($delete)
{
$this->session->set_flashdata('hasil','Deleted');
}else
{
$this->session->set_flashdata('hasil','Failed');
}
redirect('nsbh');
}
}
}
And this is what's on line 25
'id'=> $this->post('id'),
You are missing input in 'id' => $this->post('id')
So, the right code is as follow:
'id' => $this->input->post('id')
You have to use input on all other places also.
change from
$data = array( 'id' => $this->post('id'),
'name' => $this->post('name'),
'location' => $this->post('location'),
'tgl' => $this->post('tgl'),
'addrs' => $this->post('addrs'));
to
$data = array('id' => $this->input->post('id'),
'name' => $this->input->post('name'),
'location' => $this->input->post('location'),
'tgl' => $this->input->post('tgl'),
'addrs' => $this->input->post('addrs'));
As you already did in edit function
In the constructor add $this->load->library('form_validation');
So your constructor looks like this:
function __construct() {
parent::__construct();
$this->API="http://localhost/rest_ci/index.php";
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('session');
$this->load->library('curl');
$this->load->library('form_validation');
}

Yii2 Call to a member function someFunction() on Integer and a non-object

I wanna show usernames in timeline index. It show error
Call to a member function getStatusesLabel() on integer
if use this code :
'status' =>$model->data['status']->getStatusesLabel(),
and
'author' => $model->data['author']->getAuthor(),
and another error
Trying to get property of non-object
if use this code :
'author' => ArrayHelper::map($model->data['author']->getAuthor, 'id','username'),
My Model
namespace common\models;
.....
class Article extends ActiveRecord
{
.....
public function getAuthor()
{
return $this->hasOne(User::className(), ['id' => 'author_id']);
}
public function getUpdater()
{
return $this->hasOne(User::className(), ['id' => 'updater_id']);
}
public function getCategory()
{
return $this->hasOne(ArticleCategory::className(), ['id' => 'category_id']);
}
public function getArticleAttachments()
{
return $this->hasMany(ArticleAttachment::className(), ['article_id' => 'id']);
}
public static function statuses()
{
return [
self::STATUS_PUBLISHED => Yii::t('common', 'Published'),
self::STATUS_DRAFT => Yii::t('common', 'Draft'),
];
}
public function afterCreate()
{
$this->refresh();
// use common\commands\AddToTimelineCommand;
Yii::$app->commandBus->handle(new AddToTimelineCommand([
'category' => 'articles',
'event' => '_item',
'data' => [
'title' => $this->title,
'published_at' => $this->published_at,
'created_at' => $this->created_at,
'slug' => $this->slug,
'author' => $this->author_id,
'category' => $this->category,
'status' => $this->status,
]
]));
}
public function afterUpdate()
{
$this->refresh();
// use common\commands\AddToTimelineCommand;
Yii::$app->commandBus->handle(new AddToTimelineCommand([
'category' => 'articles',
'event' => '_itemU',
'data' => [
'title' => $this->title,
'published_at' => $this->published_at,
'updated_at' => $this->updated_at,
'slug' => $this->slug,
'author' => $this->author_id,
'category' => $this->category,
'status' => $this->status,
]
]));
}
}
my controller article:
public function actionCreate()
{
$model = new Article();
$transaction = Yii::$app->db->beginTransaction();
try{
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->afterCreate();
$transaction->commit();
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
'categories' => ArticleCategory::find()->active()->all(),
]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
controller timeline
public function actionIndex()
{
$searchModel = new TimelineEventSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->sort = [
'defaultOrder'=>['created_at'=>SORT_DESC]
];
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
command timeline :
class AddToTimelineCommand extends Object implements SelfHandlingCommand
{
public $category;
public $event;
public $data;
public function handle($command)
{
$model = new TimelineEvent();
$model->application = Yii::$app->id;
$model->category = $command->category;
$model->event = $command->event;
$model->data = json_encode($command->data, JSON_UNESCAPED_UNICODE);
return $model->save(false);
}
}
index timeline:
<ul class="timeline">
<?php foreach($dataProvider->getModels() as $model): ?>
<?php if(!isset($date) || $date != Yii::$app->formatter->asDate($model->created_at)): ?>
<!-- timeline time label -->
<li class="time-label">
<span class="bg-blue">
<?php echo Yii::$app->formatter->asDate($model->created_at) ?>
</span>
</li>
<?php $date = Yii::$app->formatter->asDate($model->created_at) ?>
<?php endif; ?>
<li>
<?php
try {
$viewFile = sprintf('%s/%s', $model->category, $model->event);
echo $this->render($viewFile, ['model' => $model]);
} catch (\yii\base\InvalidParamException $e) {
echo $this->render('_item', ['model' => $model]);
}
?>
</li>
view _item for index:
<div class="timeline-body">
<?php echo Yii::t('backend', 'Updated post <b>({title})</b>, published date : {published_at} ', [
'title' => Html::a($model->data['title'],
Url::to(Yii::$app->urlManager->hostInfo.'/article'.'/') .$model->data['slug'],
['target' => '_blank']),
//'author' => ArrayHelper::map($model->data['author']->getAuthor, 'id','username'),
//'author' => $model->data['author']->getAuthor(),
'author' => $model->data['author'],
'category' => $model->data['category'],
//'status' =>$model->data['status']->getStatusesLabel(),
'published_at' => Yii::$app->formatter->asDatetime($model->data['published_at']),
'updated_at' => Yii::$app->formatter->asDatetime($model->data['updated_at'])
])//.Html::a($model->data['title'], ["/article/$model->data['title']"]) ?>
</div>
what is wrong with the above code?
i was use in GridView / detailview, there is no errors
how do I fix it?
In a simple view (not based on gridview or detailView widget) that you render using eg:
return $this->render('your_view', [
'model' => $model,
]);
you can use directly the model and the attribute (or the depending function) eg:
'author' => $model->author
If you instead use a
return $this->render('your_view', [
'dataProvider' => $dataProvider,
]);
you can refer to the model instance
'author' => $dataProvider->models[i]['author']
where i is the index for the specific instance

Error Fatal error: Call to a member function insert() on a non-object

I'm using a callback after inserting in the database, to pass values to this other table, i think the method i used its fine. But it gives me this error when its inserting to the other table in the database, probably in my model, or something in the controller im kind of clueless in this error, can someone please help me.
Before someone say its to put $this->load->database(); its already in my autoload in config file :)
Fatal error: Call to a member function insert() on a non-object
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Finances::$inventory_model
Filename: controllers/finances.php
Line Number: 125
CONTROLLER:
public function inventory_management($post_array,$primary_key)
{
$this->load->model('inventory_model');
if($post_array['id_expense']!=null){
$type = 'add';
$id_exp_detail = $primary_key;
$result = $this->inventory_model->insert([
'id_exp_detail' => $id_exp_detail,
'name' => $post_array['brand'],
'quantity' => $post_array['item_quantity'],
'lote' => $post_array['package_code'];
'type' => $type,
'date' => date(),
'id_user' => $this->session->userdata('id_user'),
'id_entity' => $this->session->userdata('id_entity')
]);
}else if ($post_array['name']!=null){
$type = 'sub';
$id_treatment = $primary_key;
$result = $this->inventory_model->insert([
'id_treatment' => $id_treatment,
'name' => $post_array['name'],
'quantity' => $post_data['recomended_dose'],
'lote' => $post_array['id_package'],
'type' => $type,
'date' => date(),
'id_user' => $this->session->userdata('id_user'),
'id_entity' => $this->session->userdata('id_entity')
]);
}else{
$type = 'sub';
$id_fertilization = $primary_key;
$result = $this->inventory_model->insert([
'id_fertilization' => $id_fertilization,
'name' => $post_data['name'],
'quantity' => $post_data['quantity'],
'lote' => $post_data['id_package'],
'type' => $type,
'date' => date(),
'id_user' => $this->session->userdata('id_user'),
'id_entity' => $this->session->userdata('id_entity')
]);
}
if($result){
echo "validation Complete";
}
}
MODEL
class CRUD_model extends CI_Model
{
protected $_table = null;
protected $_primary_key = null;
// ------------------------------------------------------------------------
public function __construct()
{
parent::__construct();
}
public function insert($data)
{
$this->db->insert($this->_table, $data);
// return $this->db->insert_id();
}
MODEL:
class inventory_model extends CRUD_model
{
protected $_table = 'inventory_management';
protected $_primary_key = 'id';
// ------------------------------------------------------------------------
public function __construct()
{
parent::__construct();
}
// ------------------------------------------------------------------------
}
here is the wrong you call wrong model file
$this->load->model('inventory_model');
it should be
$this->load->model('crud_model');
and you use wrong way to pass array in function
$param = array('id_exp_detail' => $id_exp_detail, 'name' => $post_array['brand'], 'quantity' => $post_array['item_quantity'], 'lote' => $post_array['package_code'], 'type' => $type, 'date' => date(), 'id_user' => $this->session->userdata('id_user'), 'id_entity' => $this->session->userdata('id_entity'));
$result = $this->inventory_model->insert($param);

Categories