No retun in your second function?
Eloquent Query Not Working Where It works Otherwise
I have a couple simple Eloquent queries. The second one pulls data based on the first query. The first query pulls the correct data. The second pulls no data despite the same query working in my pgAdmin and in Tinker. The first query is in the following method:
function getCompanies($def=0)
{
$user = Auth::user();
$companies = Collection::make([$user->company]);
if ($user->hasRole('sys_admin') || ($user->hasRole('comp_admin') && $def == 1)){
$companies = Company::all();
}
return $companies->sortBy('name')->values();
}
This returns the result:
[{"id":1,"name":"First Company"},{"id":7,"name":"Second Company"}]
The second query, also in its own method:
function getControllers()
{
$companies = getCompanies();
\DB::enableQueryLog();
$controllers = Controller::whereIn('company_id', $companies->pluck('id')->toArray())->get();
\DB::getQueryLog();
$controllers->sortBy('name')->values();
}
As you can see I used the QueryLog to return the exact query that Eloquent is creating. The result of this is:
"query":"select * from \"controllers\" where \"company_id\" in (?, ?)","bindings":[1,7],"time":2.65
When I run this query in my pgAdmin, or even in Tinker, I get the data I'm looking for, but in the code it gives no result. Why would the Eloquent query not run when the query that is created does run in the DB?
@denewey what do you have if you dump the result of query?
function getControllers()
{
$companies = getCompanies();
$controllers = Controller::whereIn('company_id', $companies->pluck('id')->toArray())->get();
dd($controllers);
// ...
}
Note:
if you use spatie/laravel-permission package - you can replace $user->hasRole('sys_admin') || ($user->hasRole('comp_admin') with $user->hasAnyRole('sys_admin', 'comp_admin') https://spatie.be/docs/laravel-permission/v5/basic-usage/role-permissions#content-checking-roles
Please or to participate in this conversation.