Call to a member function whereHas() on a non-object in laravel - php

In my controller I have wrote this following code
$usersCount = User::where('activated', '=', 1)->where('group_id', '=', 1)->where('availability_date', '<=', $opportunity_date)->count();
$locations_array_result = explode(",",$locations_array_result);
foreach ($locations_array_result as $param)
{
$usersCount = $usersCount->whereHas('location', function($q) use($param){
$q->where('location_id', '=', $param );
});
}
This code giving following error
Call to a member function whereHas() on a non-object
Can anyone help me to find out what i have done wrong!!!

$usersCount is already a number from the 1st line of your sample.
You want instead to replace $usersCount->whereHas with User::whereHas in your foreach loop.

Taking a very wild guess here, I would think you need to get all users with these requirements
->where('group_id', '=', 1)->where('availability_date', '<=', $opportunity_date)
plus having a location_id value which exists on an array named $locations_array_result
If this is the case, this is all you need:
User::where('activated', '=', 1)->where('group_id', '=', 1)->where('availability_date', '<=', $opportunity_date)->whereIn('location_id', $locations_array_result)->get();
EDIT
Following your comment below, I assume user has many to many relation with locations (defined in your model), so eager loading and then using a condition with a callback should do the job:
$users = User::where('activated', '=', 1)
->where('group_id', '=', 1)
->where('availability_date', '<=', $opportunity_date)
->with(array('location' => function($query) use ($locations_array_result)
{
$query->whereIn('location_id', $locations_array_result);
}))->get();

Related

Trying to get property of non-object error in Laravel when assigning an ID to a variable

I'm getting the row in the following code :
$grpusrow = DB::table('grpusrs')
->where('group_id', $id)
->where('user_id', $u_id)
->get();
And then getting the ID in this line :
$grpusrid = $grpusrow->id;
I receive the following error on the line in number 2 :
Trying to get property of non-object
->get() will always return multiple objects at once. You're simply not telling it which index of $grpusrow to get the ID from.
$grpusrows = DB::table('grpusrs')
->where('group_id', $id)
->where('user_id', $u_id)
->get();
foreach ($grpusrows as $grpusrow) {
dump($grpusrow->id);
}
// Or
$grpusrow = DB::table('grpusrs')
->where('group_id', $id)
->where('user_id', $u_id)
->first();
dump($grpusrow->id);
Maybe 2 solutions:
If you want a unique row in return (with a primary key in arguments for example), you should try ->first() instead of ->get().
The problem is the using of where clauses, I think it works with array when you want more than one where clause, try like this :
->where([['group_id', '=', $id],['user_id', '=', $u_id]])->get(); ( or first() )

How to access varible inside orWhere() in laravel query builder|Laravel

I am trying to build little complex query where everything wan OK until I tried to use a advanced where condition.
In the code below I am getting an error saying
ErrorException: Undefined variable: user in file D:...**\app\Http\Controllers\ApiAuthController.php on line 285
and the line 285 is $query->where("tbl_transactions.from_user_id", "=", $user->id) inside the orWhere()
public function loadTransactions()
{
$token = JWTAuth::getToken();
$user = JWTAuth::toUser($token);
return DB::table('tbl_transactions')
->join('tbl_users as fromu', 'fromu.id', '=', 'tbl_transactions.from_user_id')
->join('tbl_users as tou', 'tou.id', '=', 'tbl_transactions.to_user_id')
->select('tbl_transactions.id', 'tbl_transactions.from_user_id', 'tbl_transactions.to_user_id', 'tbl_transactions.amount', 'tbl_transactions.created_at', 'tbl_transactions.status', 'fromu.userid', 'tou.userid', 'tou.phone as tophone', 'fromu.phone as fromphone')
->orWhere(function ($query) {
$query->where("tbl_transactions.from_user_id", "=", $user->id)// here the problem is (undefined **$user**)
->where('tbl_transactions.to_user_id', '=', $user->id);
})
->orderBy('tbl_transactions.id', 'desc')
->take(50)
->get();
}
I am new to laravel.Anyone here could help me would be great.
You need to use the use clause to make the variable accessible in the closure scope. So, change this:
->orWhere(function ($query) {
To this:
->orWhere(function ($query) use($user) {
Im too lazy to link the other 100s of posts that are duplcates of this.
PHP manual - anonymous functions Example #3

cant get the data I want from two different tables using Laravel

I have a table called instructor_class: user_id, class_id and I have another table classes: id, time, active.
I would like to show classes for a single user but only those classes that active is 0 or 1.
My current code looks like this:
return InstructorClass::with('classes.session')->where('user_id', '=', $userId)->get();
This code is displaying me everything, then I tried the following code:
$active = 1;
return InstructorClass::with(['classes' => function ($q) use ($active) {
$q->where('active', '=', $active); // '=' is optional
}])
->where('user_id', '=', $userId)
->get();
This again returns me same records, but of course the class property is null for each record, which at some point looks correct, but my point is if the 'active' field does not corresponds at the classes table do not show the record, seems like the where() stm within with() is optional..
I am kinda stuck here...
Would appreciate your help, opinions!
You can use ::has('classes') to only return the models that have related classes
return InstructorClass::has('classes')->with(['classes' => function ($q) use ($active) {
$q->where('active', $active);
}])
->where('user_id', '=', $userId)
->get();
Never thought it could be this simple:
return InstructorClass::with('classes.session')
->join('classes', 'classes.id', '=', 'instructor_class.class_id')
->where('classes.active', '=', 1)
->where('user_id', '=', $userId)
->get();

Method render does not exist laravel pagination

$page = Question::paginate(10);
dd($page);
Here the pagination working very well but when i use pagination with other models relations then its produce the paginate result but pagination links not appear because its produce error
$questions = Course::with(['questions' => function($query){
$query->paginate(10);
},'questions.subjects','questions.years'])
->where("status",1)
->where(function ($query) use ($course) {
$query->orWhere('course', '=', $course)
->orWhere('slug', '=', $course);
})->get();
ERROR :
BadMethodCallException in Macroable.php line 81:
Method render does not exist.
What is missing here.
Paginate should be used at the end of a query, and not in relations:
$questions = Course::with(['questions','questions.subjects','questions.years'])
->where("status",1)
->where(function ($query) use ($course) {
$query->orWhere('course', '=', $course)
->orWhere('slug', '=', $course);
})->paginate(10);
Since you are not paginating the main result set, you get the Method render does not exist error.

Adding conditions to Laravel has()

I have a table named answers and its columns are id, answers, batch, candidate_id. I want to get all candidates that has no record of answers under batch number of 1.
Is there a way to add condition to this statement (this is in my candidate model) ?
return $this->has('answers', '=', 0)->get();
I tried this way but it didn't work:
return $this->has('answers', '=', 0)->whereBatch(1)->get();
You need whereHas:
$this->whereHas('answers', function ($q) {
$q->whereBatch(1);
}, '=', 0)->get();
Btw this is exactly the same as calling has with closure as 5th param:
$this->has('answers', '=', 0, 'and', function ($q) {
$q->whereBatch(1);
})->get();

Categories