Laravel returning LogicException "must return a relationship instance." - eloquent

I am getting the error whenever the function getCips is being called:
App\Models\Employee::getAllCips must return a relationship instance.
The function that is causing this error is:
private function getCips($user, $page, $search){
if($page == null)$page = 1;
$count = 7;
$cips = null;
if(get_class($user) == User::class)
{
$cips = Visitable::all()->whereNotNull('cip');
}else{
$cips = $user->getAllCips(); //The error is caused because of this line.
}
if($search!=null){
$cips = $cips->filter(function($cip, $i)use($search){
return strpos($cip->name, $search)!==false||strpos($cip->email, $search)!==false||strpos($cip->phone, $search)!==false||strpos($cip->location->name, $search)!==false||strpos($cip->cip->Associated_hospital, $search)!==false;
});
}
$lastPage = ($cips->count()%$count == 0)? intdiv($cips->count(), $count):intdiv($cips->count(), $count)+1;
$page = ($cips->count() == 0)?0:intval($page);
return ["cips"=>$cips->values()->skip(($page-1)*$count)->take($count)->all(),"lastPage"=>$lastPage, "currentPage"=>$page];
}
As marked in the line of code above, the $user is an instance of Employee class.
Now the function getAllCips() in class Employee is as:
public function getAllCips():Collection{
$allCips = $this->headQuarter->getAllCips();
foreach($this->subordinates as $subordinate){
$allCips = $allCips->concat($subordinate->getAllCips);
}
return $allCips;
}
I am using Laravel 8. It would be very helpful if anybody could point out what I am doing wrong here.

Related

Codeigniter Call to a member function where() on bool

I tried to set seen to any contact data in database, but when i try that:
public function showMessage($id){
$this->load->model('Message_Model');
$messageData = $this->Message_Model->selectMessage($id);
if($messageData[0]->messageIsSeen == 0){
$this->Message_Model->setSeenToMessage($id);
}
$data = array('messageData' => $messageData[0]);
$this->load->view('Back/MessageDetail', $data);
}
Model:
function setSeenToMessage($id){
$this->db->update('messages', array('messageIsSeen' => 1))->where('messageId', $id);
return 1;
}
It throws that error
i solved it like this change
function setSeenToMessage($id){
$this->db
->where('messageId', $id);
->update('messages', array('messageIsSeen' => 1))
return 1;
}
nevertheless, still i don't know how did it works

Why I'm getting the error: "Parameter 1 to Credis_Client::scan() expected to be a reference"?

I'm trying to call this class function:
public function scan(&$Iterator, $pattern = null, $count = null)
{
return $this->__call('scan', array(&$Iterator, $pattern, $count));
}
From my class:
$itScan = NULL;
while($arr_keys = $this->redisClient->scan($itScan, '', 10000)) {
foreach($arr_keys as $str_key) {
echo "Here is a key: $str_key\n";
}
}
I understand this is something related to the & pointer but I can't figure who to call it from inside my class.
Thank you!
This is the proper way to iterate over your results :
$i = null;
$allResults = [];
do {
$someResults = $redis->scan($i, "*", 10000);
if (!empty($someResults)) {
$allKeys = array_merge($allKeys, $someResults);
}
}
while ($i);

Zend form validation multiple custom validation message for same field at the same time

I have a Zend form password custom validation.
I have set the addValidator functions IInd argument to false since I need to get all errors at once. Both of my validation classes have set the self::INVLID to corresponding error messages.
But when I look in the Zend controller even though both validations fail I'm getting only one (the last) error message.
I need all the error messages at once.
/* Form validation*/
$passwordSpecialValidator = new Passwordspecialvalidationvalidator();
$passwordHistoryValidator = new Passwordhistorylvalidationvalidator(new model(), $username, $newpass);
$this->newpass->addValidator($passwordSpecialValidator, false)
->addValidator($passwordHistoryValidator, false);
/* One validation class */
class Passwordhistorylvalidationvalidator extends Zend_Validate_Abstract {
const INVLID = '';
protected $_messageTemplates = array(
self::INVLID => 'Your password doesnt meet the history requirements'
);
public function __construct($model, $username, $password) {
$this->_model = $model;
$this->_username = $username;
$this->_password = $password;
}
public function isValid($value, $context = null) {
if ($this->_username == "") {
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$arrayResult = $auth->getIdentity();
if (isset($arrayResult->username)) {
$this->_username = $arrayResult->username;
}
}
}
$passwordExists = false;
$oldPasswords = $this->_model->getHistoryPasswords($this->_username, $this->_password);
if (count($oldPasswords) > 0) {
$passwordExists = true;
}
if ($passwordExists == false) {
return true;
} else {
$this->_setValue($value);
$this->_error(self::INVLID);
return false;
}
}
}
/* Getting error messages */
foreach ($objForm->getMessages() as $messages) {
foreach ($messages as $message) {
$errMessages[] = $message;
}
}
But the array $errMessages has only the last validation message (without index) even though both special validation and history validation fails. How would I get both error messages in an array if both validations fail?

Zend db select how to know return zero rows?

This is my code:
public function is_existing($url) {
$query = $this->select()
->where("url=?",$url);
if(!$query) {
return false;
} else {
$row = $this->fetchRow($query);
$row = $row->toArray();
return $row;
}
}
But sometimes, I receive
Fatal error: Call to a member function toArray() on a non-object in...
Is it right to use if(!$query) to check the existing rows in DB?
Change your code to this
public function is_existing($url) {
$query = $this->select()
->where("url=?",$url);
$row = $this->fetchRow($query);
if(!$row) {
return false;
} else {
return $row->toArray();
}
}
Because $query object will always be created irrespective $url matches record or not hence will always pass if condition .
Is it right to use if(!$query) to check the existing rows in DB ?
No, you should evaluate the result of fetchRow to determine if there are results, fetchRow either returns a Zend_Db_Table_Row or null if no rows are found.
public function is_existing($url) {
$query = $this->select()
->where("url=?",$url);
$row = $this->fetchRow($query);
if(is_null($row)) {
return false;
} else {
return $row->toArray();
}
}

Entity Framework 4.0 Error The object could not be added or attached EntityReference has EntityKey value that does not match EntityKey

Hi everybody im starting to work with Entity Framework 4.0 and ASP.NET 4.0 i'm trying to make a master detail web page and i'm having problems when i try to add new items to a previously recorded items below is the i made for this:
private void guardarOrdenMedicamento()
{
InventarioSIAIplusEntities SIAplusContext = (InventarioSIAIplusEntities)(Session["context"]);
InvOrden orden;
string resultMessage;
if (DetalleMedicamentosOrden.Count == 0)
{
MessageBox1.ShowError("Debe especificar al menos un medicamento para la orden.");
return;
}
if (txtIDorden.Text.Trim() == "")
{
orden = new InvOrden();
orden.IDcentro = Convert.ToInt32(ddlCentros.SelectedValue);
orden.estado = ddlEstadoOrden.SelectedValue;
orden.fecha = Convert.ToDateTime(txtFechaCreacion.Text);
orden.comentario = txtComentarioOrden.Text;
orden.usuarioCrea = "Jeanc";
SIAplusContext.AddToInvOrdenes(orden);
resultMessage = "La orden fue registrada satisfactoriamente";
}
else
{
int idorden = Convert.ToInt32(txtIDorden.Text.Trim());
orden = SIAplusContext.InvOrdenes.Where(c => c.IDorden == idorden).First();
orden.estado = ddlEstadoOrden.SelectedValue;
orden.fecha = Convert.ToDateTime(txtFechaCreacion.Text);
orden.comentario = txtComentarioOrden.Text;
orden.usuarioCrea = "Jeanc";
resultMessage = "La orden fue actualizada satisfactoriamente";
foreach (var item in DetalleMedicamentosOrden)
{
if (item.IDorden == 0)
{
// item.IDorden = idorden;
// item.InvOrdenReference.EntityKey = orden.EntityKey;
//neww System.Data.EntityKey("InventarioSIAIplusEntities.InvOrdenes", "IDorden", orden.IDorden);
// SIAplusContext.AddToInvOrdenDets(item);
item.InvOrden = orden;
//
// SIAplusContext.AddToInvOrdenDets(item);
//orden.InvOrdenDets.Add(item);
}
else
{
InvOrdenDet det = SIAplusContext.InvOrdenDets.Where(c => c.IDorden == item.IDorden && c.IDmedicamento == item.IDmedicamento).First();
det.cantidadApr = item.cantidadApr;
det.cantidadSol = item.cantidadSol;
det.comentario = item.comentario;
}
}
}
SIAplusContext.SaveChanges();
}
The Error is :The object could not be added or attached because its EntityReference has an EntityKey property value that does not match the EntityKey for this object.
Thanks For any help with this.
I think that the problem is here:
item.InvOrden = orden;
You either have to use AddObject or update the values of an existing object.