Laravel query returns builder instead of collection - php

I am new to laravel and trying to have a result.
My code is this:
class GegonosController extends Controller
{
public function index($gid = null, $cid = null, $nid = null)
{
if (is_null($cid) and is_null($nid) and is_null($gid)) {
$gegon = Gegono::orderBy('created_at','desc')->get();
}
else{
if(!is_null($gid)) {
if($gid == 0) {
$gegon = Gegono::where('gegtype_id','>',1);
}
else{
$gegon = Gegono::where('gegtype_id', '=', $gid);
}
}
else {
$gegon = Gegono::where('gegtype_id','>',0);
}
if (!is_null($cid)) {
$gegon->where('city_id', '=',$cid);
}
if (!is_null($nid)) {
$gegon->where('nomos_id','=', $nid);
}
$gegon->orderBy('created_at','desc')->get();
}
$nomoi = \App\Nomoi::orderby('name')->get();
return view('front.gegonota', compact('gegon','gid','cid','nid','nomoi'));
}
In the first, if when all variables are null the result is a collection of all the records of the table.
In all other, if (other cases) the result is a builder and I get no results,
It doesn't show any error but gives no results.
Any help would save me a lot of time.

Query Builder's get() method returns the collection of records. In your code, you just call get() method in the air, so it does nothing. You should assign it to a variable or use it in an expression.
Source: https://laravel.com/docs/5.4/eloquent#collections

Related

Laravel ERROR: Creating default object from empty value in Excel Import

While trying to update database using Excel:
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
$this->gradelevel = $row['grade_level_code'];
$employeegrade = HrEmployee::where('company_id',auth()->user()->company_id)->where('employee_code', $row['staff_id'])->where('email', $row['official_email']) ->first();
$employeegrade->grade_level_id = $this->getGradeLevel();
$employeegrade->save();
}
}
public function getGradeLevel(){
if(!empty($this->gradelevel) || !$this->gradelevel){
return HrGradeLevel::where('grade_level_code',$this->gradelevel)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
} else {
return 0;
}
}
I got this error:
production.ERROR: Creating default object from empty value
and it points to this line:
$employeegrade->grade_level_id = $this->getGradeLevel();
How do I get this resolved?
most probably this will return null
$employeegrade = HrEmployee::where('company_id',auth()->user()->company_id)->where('employee_code', $row['staff_id'])->where('email', $row['official_email']) ->first();
You can also use firstOrNew() if not exist then will create new object of HrEmployee
$employeegrade = HrEmployee::firstOrNew(array("column"=>value, "column2"=>value));
if you want update the existing record only use as
$employeegrade = HrEmployee::where('company_id',auth()->user()->company_id)->where('employee_code', $row['staff_id'])->where('email', $row['official_email']) ->first()
if(!$employeegrade){
//log error employee nit found
}else
{
//update record
}

OctoberCMS Pagination

I use octobercms and User Extended plugin(Clacke). I try to render a pagination because for now i have a lot of registered users and they display on one page.
I use random users function from \classes\UserManager.php
public static function getRandomUserSet($limit = 7)
{
$returner = new Collection;
$userCount = User::all()->count();
if(!isset($userCount) || empty($userCount) || $userCount == 0)
return [];
if($userCount < $limit)
$limit = $userCount;
$users = User::all(); //paginate(5)
if(empty($users))
return $returner;
$users->random($limit);
$friends = FriendsManager::getAllFriends();
foreach($users as $user)
{
$userAdd = true;
if(!$friends->isEmpty())
{
foreach($friends as $friend)
{
if($user->id == $friend->id)
{
$userAdd = false;
break;
}
}
}
if($user->id == UserUtil::getLoggedInUser()->id)
$userAdd = false;
if($userAdd)
{
$returner->push($user);
}
}
return $returner->shuffle();
}
try to do this with changing return $returner->paginate(25); and $users = User::paginate(25); but throws me an error
An exception has been thrown during the rendering of a template
("Method paginate does not exist.").
After that i try to change directly in \components\User.php
public function randomUsers()
{
return UserManager::getRandomUserSet($this->property('maxItems'))->paginate(12);
}
But again the same error.
Tryed and with this code and render in default.htm {{ tests.render|raw }}
public function randomUsers()
{
$test = UserManager::getRandomUserSet($this->property('maxItems'));
return $test->paginate(10);
}
Again with no success. Could anyoune give me some navigation and help to fix this?
If you are using random users function from \classes\UserManager.php
I checked the code and found that its using Illuminate\Support\Collection Object. So, for that Collection Object pagination works differently
You need to use forPage method.
On the other hands paginate is method of Illuminate\Database\Eloquent\Collection <- so both collection are not same
Use forpage
// OLD return UserManager::getRandomUserSet($this->property('maxItems'))
// ->paginate(12);
TO
return UserManager::getRandomUserSet($this->property('maxItems'))
->forPage(1, 12);
forPage method works like forPage(<<PAGE_NO>>, <<NO_OF_ITEM_PER_PAGE>>);
so if you use forPage it will work fine.
if any doubt please comment.

Codeigniter not getting data though available in mysql database

I have a model which fetch the data from database is below
public function counselor() {
$inst_id = $this->session->userdata('user_id');
$submission_key=$this->session->userdata('submission_key');
$query = $this->db->query("SELECT * FROM counselor where USER_ID = $inst_id AND submission_key= $submission_key");
$data = $query->num_rows();
if ($data > 0) {
return $data;
} else {
return false;
}
}
I have tested the $inst_id and $submission_key by printing it and its set.
$inst_id=2 and $submission_key=2016-8 .BUT though I have one record in database with those two field set its not returning the data. What is the case. I have tried with codeigniter get() and where() method too. Still not giving me the result.
Just write your query using active record function. It will help you in escaping string
$this->db->select('*',FALSE);
$this->db->where('USER_ID',$inst_id);
$this->db->where('submission_key',$submission_key);
$query=$this->db->get('counselor');
$data = $query->num_rows();
if ($data > 0) {
return $data;
} else {
return false;
}

How to search for multiple values in a single field of mysql table using codeigniter active record?

I have to search for multiple values in a field using mysql in codeigniter. Here follows my code.
In Controller
public function vpsearch()
{
$data['info'] = $this->psearch_m->emp_search_form();
$this->load->view("employer/result",$data);
}
IN Model
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
$jrole = $this->input->post('ps_jobrole'));
if ( $jrole !== NULL)
{
return $this->db->get('js_edu_details');
$this->db->like('js_skills','$skill');
}
}
In view i.e, (../employer/result)
foreach($info->result() as $row)
{
echo $row->js_id."<br/><br/>" ;
}
However I am getting all the records in 'js_edu_details' table instead of fields having searched 'skills'.
Where I am going wrong? Any help wud b appreciated, thanx in advance.
Try:
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
//$skill = $this->input->post('ps_skills', true); other short way of getting the above result with `xss clean`
if ( $jrole !== NULL)
{
$this->db->like('js_skills',$skill); #remove the single quote around the `$skill`
$res = $this->db->get('js_edu_details');
echo $this->db->last_query(); #try to print the query generated
return $res;
}
}
Return statement should be after the like statement
You should arrange the code properly like this
public function emp_search_form()
{
$ps_skills = $this->input->post('ps_skills')
$skill = $this->security->xss_clean($ps_skills);
if ( $jrole !== NULL)
{
$this->db->like('js_skills','$skill');
return $this->db->get('js_edu_details');
}
}
Also you should note the condition will never meet. It will always give error undefined variable $jrole

Two different functions one works one calls a non-object

I have two functions getCompanyDetails and getHostingDetails
The first database getCompanyDetails works fine but the getHostingDetails shows
Trying to get property of non-object
getCompanyDetails:
Controller: $data['companyName'] = $this->quote->getCompanyDetails()->companyName;
Model:
public function getCompanyDetails()
{
$this->db->select('companyName,companySlogan,companyContact,
companyEmail,companyWebsite,companyPhone,
companyFax,companyAddress');
$this->db->from('companyDetails');
$result = $this->db->get();
if($result->num_rows()<1)
{
return FALSE;
}else{
return $result->row();
}
}
getHostingDetails:
Controller:
$data['hostingRequired'] = $this->quote->getHostingDetails()->hostingRequired;
Model:
public function getHostingDetails()
{
$this->db->select('hostingRequired,domainRequired,domainToBeReged,
domaintoBeReged0,domainTransfer,domainToBeTransfered,
domainToBeTransfered0,currentHosting');
$this->db->from('hostingDetails');
$result = $this->db->get();
if($result->num_rows()<1)
{
return FALSE;
}else{
return $result->row();
}
}
Well, one method returns an object from $result->row() and the other false. You can't call a method on false.
false is returned when no record is found. So you need to check the return value before using it.
Well in your get functions chances is your code might return you false if there is no rows returned. You might want to check before retrieving the details. Example:
$details = $this->quote->getHostingDetails();
if($details){
$data['hostingRequired'] = $details->hostingRequired;
}
The problem is probably how you use those functions in your controller. If any of them returns FALSE, then
$this->quote->getHostingDetails()->hostingRequired;
is going to give you errors. Try
if ($row = $this->quote->getHostingDetails()) {
echo $row->hostingRequired;
}

Categories