Eloquent User Where Clause with Entrust Library - laravel

I'm trying to select all users for a company. But only users who has "admin" role status (Entrust, etc.).
User::where('company_id', Auth::user()->company_id)->hasRole('admin')->get();
The above is throwing an error. Left a bit lost on how to run such a query. Where am I going wrong with this? Very little documentation on Entrust.

You can use plain Eloquent for this. The whereHas method would generate one query:
$users = User::where('company_id', Auth::user()->company_id)
->whereHas('roles', function($query) {
$query->where('name', 'admin');
})->get();
Or, you can just get the roles and then get all of that role's users. This would generate two queries, but ultimately achieve the same thing.
$users = Role::where('name', 'admin')
->first()
->users()
->where('company_id', Auth::user()->company_id)
->get();

Think you need to get all the users having the company_id first
$users = User::where('company_id', Auth::user()->company_id)->get();
Then loop through $users and check hasRole()
foreach ($users as $user) {
if($user->hasRole('admin')){
//user is admin
}
}
UPDATE
This might be a dirty solution but you can try to do a manual query
$admin = DB::table('role_user')
->join('users', 'users.id', '=', 'role_user.user_id')
->join('roles', 'roles.id', '=', 'role_user.role_id')
->where('roles.name', 'admin')->get();

Related

How create a subquery with eloquent and laravel with softdeletes

I am using Laravel 7 and Vue.js 2.
I want to retrieve the tasks that are not assigned to a specific user.
I made the following code that works correctly.
$tasks_user = TaskUser::select('task_id')
->where('user_id', $id)
->get();
$tasks = Task::select('tasks.id as id', 'tasks.name as name', 'tasks.description as description')
->join('task_user', 'tasks.id', '=', 'task_user.task_id')
->whereNotIn('task_user.task_id', $tasks_user)
->distinct()
->get();
By the way to be more elegant I decided to transform the above code into a single query as follows:
$tasks = Task::select('tasks.id as id', 'tasks.name as name', 'tasks.description as description')
->join('task_user', 'tasks.id', '=', 'task_user.task_id')
->whereNotIn('task_user.task_id', function($q) use ($id)
{
$q->select('task_id')
->from('task_user')
->where('user_id', $id)
->get();
})
->distinct()
->get();
Unfortunately I discovered that the above query didn't work because it doesn't considers softdeletes.
For example, if the user with id 3 was related with the task 7 but now that row has been deleted with softdeletes in the table task_user, the first code returns also the task with id 7 (correctly) and the second one not (uncorrectly).
So finally, I must do a single query that works as the first code.
Can help?
You can actually combine both approaches. whereNotIn accepts also an Eloquent Query, it doesnt need to be a callback. Try this:
$userRelatedTasksQuery = TaskUser::select('task_id')
->where('user_id', $id);
$tasks = Task::select('tasks.id as id', 'tasks.name as name', 'tasks.description as description')
->join('task_user', 'tasks.id', '=', 'task_user.task_id')
->whereNotIn('task_user.task_id', $userRelatedTasksQuery)
->distinct()
->get();
Be sure to not use get() at the end of the $userReleatedTasksQuery, as you want the eloquent query instance, not the result.

How to Write Sub Query in With()?

I have to get specific data like "roles" table have filed status and i need status = 1 that all data get from the role table
$result = User::select()
->with('roles')
->where('email', $email)
->get();
return $result;
Following the answers to this question: Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?
If I understood correctly how your data model is structured:
User has many Roles
Role has a property status
Want to filter by status = 1
$users = User::whereHas('roles', function($q){
$q->where('status', '1');
})
->where('email', $email)
->get();
EDIT: I am not happy with the answer above because in that case as far as I understood, the Users returned do not have the list of roles already loaded, so I checked the documentation (https://laravel.com/docs/5.8/eloquent-relationships) and given what I found, the following code should do what you ask:
$users = User::with(['roles' => function ($query) {
$query->where('status', '1');
}])
->where('email', $email)
->get();
I never used eloquent nor laravel and I am not a php developer, so I could not try this snippet, please if it is not correct let me know.
You can write subQuery like
$result = User::select()
->with(['roles' => function($q){
$q->where('status', 1);
}])
->where('email', $email)
->get();
return $result;

Order by related table column

I have a query like:
$users = User::with('role')
->get();
How can I order the results by the related table, so it's something like:
$users = User::with('role')
->orderBy('role.id', 'DESC')
->get();
Is there a way to do it without joining the role table (since we're already doing with('role')?
what are you trying to order. the list of users or the roles.
if you are trying to sort the users base on role do.
$users = User::with('role')->orderBy('role_id', 'DESC')
->get();
if you are trying to sort the roles of the user then pocho's answer is correct.
$users = User::with(array('role' => function($query)
{
$query->orderBy('id', 'DESC');
}))->get();
From the documentation:
$users = User::with(array('role' => function($query)
{
$query->orderBy('id', 'DESC');
}))->get();
You can also do a raw query using DB::raw like in the examples here.
You can always sort the returned collection quite easily...
$users = User::with('role')
->get()
->sortBy(function($user, $key)
{
return $user->role->id;
});
This is assuming a user hasOne or belongsTo a role. If your relationship is something that can return multiple roles, then it becomes a bit more complex because you need to decide which of the user's roles to sort by.

How to select instances with multiple relations?

I have some models Featured_Course_Request, Course_Request, Response and Teacher. Featured_Course_Request hasOne Course_Request and Course_Request hasMany Response by Teacher.
I want to get the only Featured_Course_Requests on which logged in teacher has not responded (have no Response by logged in teacher.) How can I do it?
I am trying to achieve it with the following code but it is not giving correct output.
$featured_course_request = Featured_Course_Resquest::whereRaw('remaining_coins >= coins_per_click')->where('status', '=', 'open')
->whereHas('courseRequest', function($q) use ($teacher){
$q->whereHas('responses', function($qe) use ($teacher){
$qe->where('teacherID', '!=', $teacher->id);
});
});
You can target nested relations with the dot syntax: 'courseRequest.responses' further more you'll need whereDoesntHave instead of whereHas:
$featured_course_request = Featured_Course_Resquest::whereRaw('remaining_coins >= coins_per_click')
->where('status', '=', 'open')
->whereDoesntHave('courseRequest.responses', function($q) use ($teacher){
$qe->where('teacherID', '=', $teacher->id);
})
->get();

Laravel: how to query to get all records except where relation has name column = admin

I have this query
$users = User::whereHas('roles', function($q){
$q->where('name', '!=', 'admin');
})->get();
but I want to get all users including the ones that have no roles associated. Is there a way to query this?
You want to get the users where the number of roles matching 'admin' is less than one:
$users = User::whereHas('roles', function($q){
$q->where('name', 'admin');
}, '<', 1)->get();
whereHasNot is coming, but not in a release yet.

Resources