toArray give error in cakephp 3.0 - cakephp-3.0

I want to get all product related to 'products' table. But when $product_key blank
,the code will give errors. I want the blank array without elements. My code in the controller like that.
$ProductTable = TableRegistry::get('products');
$ProductData = $ProductTable->find('All') ->where(['product_key' => $product_key]) ->first() ->toArray();

You should put the {$ProductData} inside if condition like this:
$ProductTable = TableRegistry::get('products');
$ProductData = $ProductTable->find('All') ->where(['product_key' => $product_key]) ->first();
if($ProductData){
$ProductData = $ProductData->toArray();
}else{
$ProductData = [];
}

Related

Trying to get property 'name' of non-object when trying to click next page using pagination

I get an error saying "Trying to get property 'name' of non-object" when I tried to click on next page using pagination.
Here is my Controller:
$websites = Website::all();
$menu = Menu::with('categories')->whereHas('categories', function ($query) {
$query->where('slug', request()->category);
})->paginate(8);
$categories = Category::all();
$categoryName = $categories->where('slug', request()->category)->first()->name;
return view('shopmenu')->with([
'menu' => $menu,
'categories' => $categories,
'categoryName' => $categoryName,
'websites' => $websites,
]);
The error is in this code:
$categoryName = $categories->where('slug', request()->category)->first()->name;
How do I solve this?
You need to put check if you are getting any record then try to access name.
$categoryName = $categories->where('slug', request()->category)->first();
if ($categoryName) {
$categoryName = $categoryName->name;
}
Basically due to chaining when you get null in this query $categories->where('slug', request()->category)->first() and you try to access name property on null you get this error.

Keep sort order of json columns in Laravel after inserting new Key Value pair

I have a key value pair that I am inserting into a model with the following:
public function addContactDetail(Request $request){
$data = $request->all();
$contact_id = $data['contact_id'];
$contact = Contact::find($contact_id);
$details = $contact->details;
$details[$data['label']] = $data['value'];
$contact->details = $details;
$contact->save();
return response()->json($contact);
}
After insert it sometimes puts it randomly in the middle of the object. How do I keep it at the end?
If you are using Laravel 5 or greater version,
Try casting your json column into array in eloquent using mutators. like this.
inside your Contact Model
protected $casts = [
'details' => 'array',
];
By doing so, I guess you will get what you want. Try it and let me know

How to fetch data from database with 3 parameters Laravel

I'm still new to this laravel, for now I'm facing a trouble for fetching data from the database. What i want to get is when there are only one data available, the second parameters won't be executed, but if there are some data available on the second parameters, then all the data from first parameter and the second parameter will be called.
$detail = Barang_Keluar_Detail::findOrFail($id); //15
$cariid = $detail->pluck('barang_keluar_id');
$instansiquery = Barang_Keluar::where('id',$cariid)->first(); //21
$instansiid = $instansiquery->pluck('instansi_id');
$tanggal = $instansiquery->pluck('tanggal')->first();//2019-12-31
and the parameter are here
$cariinstasama = Barang_Keluar::where('id', $cariid)
->orWhere(function ($query) use($instansiid, $tanggal) {
$query->where('tanggal', "'$tanggal'")
->where('instansi_id', $instansiid);
});
Please any help will be appreciated, thank you.
Laravel query builder provides elegant way to put conditional clause using when() . You can put conditional clause on your query like this:
$cariinstasama = Barang_Keluar::where('id', $cariid)
->when($instansiid, function ($query, $instansiid) {
return $query->where('instansi_id', $instansiid);
})
->when($tanggal, function ($query, $tanggal) {
return $query->where('tanggal', $tanggal);
})->get();
For more info see https://laravel.com/docs/5.8/queries#conditional-clauses
You can try this as well.
$cariinstasama = Barang_Keluar::where('id', $cariid);
if($instansiid !== null)
{
$cariinstasama->where('instansi_id', $instansiid);
}
if($tanggal !== null)
{
$cariinstasama->where('instansi_id', $instansiid);
}
$result = $cariinstasama->get();
Its not clear what exactly you want.
Are you applying more than one parameter on the query if the first parameter result gives you more than one row in the database? If yes check out my approach :
$query = new Model(); // the model you want to query
if($query->where('col1', $param1)->count() > 1) // checks if the query from the 1st parameter produces more than one row in the database
$query = $query->where( // if yes apply more parameters to the query
[
['col1', $param1],
['col2', $param2]
]
);
else
$query = $query->where('col1', $param1);
$results = $query->get();
Hope it helps....

Yii2: Conditional fill of Json data

I have a table ipd_charges like
id doctor_name charges_cash charges_cashless
1 1 300 600
2 2 200 400
and in my controller the code is like this which is working fine
public function actionCharges($id){
$model= \app\models\IpdCharges::findOne(['doctor'=>$id]);
return \yii\helpers\Json::encode([
'visit_charges'=>$model->charges_cash,
]);
}
Now what I want is to fill the data on condition and tried to modify the above code which is only returning the first condition in either case
public function actionCharges($id){
$model= \app\models\IpdCharges::findOne(['doctor'=>$id]);
$query = (new \yii\db\Query())
->select('tpa_name')
->from('patient_detail')
->innerJoin('daily_ward_entry',
'daily_ward_entry.general_regn_no = patient_detail.general_regn_no')
->where(['daily_ward_entry.id'=>$id]);
$command = $query->createCommand();
$rows = $command->queryAll();
if ($rows['tpa_name'] === NULL){
return \yii\helpers\Json::encode([
'visit_charges'=>$model->charges_cash,
]);
}else {
return \yii\helpers\Json::encode([
'visit_charges'=>$model->charges_cashless,
]);
}
}
Need a little clue what I am doing wrong here?
$model1= \app\models\Tpa::findOne(['tpa_name']);
You are specifying this condition wrong. You only provide column name without any condition.
Also you need to check $model for existence too.

Zend Framework - join query

I build a function
public function getBannedByLogin($commentId)
{
$sql = $this->getDbAdapter()->select()
->from(array('comments' => 'comments'), array())
->join(array('users' => 'qengine_users'),
'comments.bannedBy = users.userId',
array())
->where('commentId = ?', $commentId)
;
$row = $this->fetchRow($sql);
return $row['login'];
}
And there are problems, that does'nt work! :D
Let's I explain you. Column 'bannedBy' from comments returns id of user, who give a ban. I need to join this with table users to load a login field. Where i have mistakes?
I assume the code works in the sense of not throwing an exception. If so, your code is OK, you just specifically tell Zend_Db not to select any columns.
public function getBannedByLogin($commentId)
{
$sql = $this->getDbAdapter()->select()
->from(array('comments' => 'comments'))
->join(array('users' => 'qengine_users'),
'comments.bannedBy = users.userId')
->where('commentId = ?', $commentId)
;
$row = $this->fetchRow($sql);
return $row['login'];
}
The last argument to from() and join() functions is an array of columns you wish to select. If you pass in an empty array, no columns are selected. No argument = select everything. You can, of course, specify only the columns you need too.