Sort Users based on specific Value(string) in Laravel - laravel

I want to sort users based on the specific value. For example I have Users table and has relation with Profiles Table. In the Profiles table I have saved Country (string) of the user.
Now I want to sort specific country users first and then the other country Users.
Please guide me how can I do this in Laravel.
Thanks

You can play with that code.
$users = Users::with(['profiles' => function ($query) {
$query->where('country', 'USA');
$query->orWhere('country', 'Poland')
}])->get();

I have not check this but You may try this solution. It will help you.
$users = Users::with(['profiles' => function ($query) {
$query->orderBy("country='your country name'", 'DESC')
$query->orderBy('country', 'ASC')
}])->get();

You can use this
$users = Users::with(['profiles' => function ($query) use($country) {
$query->orderBy(DB::raw('case when country="'.$country.'" then 1 else 2 end'))->orderBy('country', 'ASC');
}])->get();

Related

Grouping related models by pivot

I'm trying to group related model by pivot data, but this returns only one record of the related for each group. How can I group quiz records by column parent, which is saved in pivot table?
$user = User::where('id', $id)
->with(['quiz' => function($query) use ($md) {
$query->where('md_id',$md)->groupBy('pivot_parent');
}])
->first();
Try this and let me know what did you got
$user= User::where('id', $id)->whereHas('quiz', function($query)
use($md){
$query->where('md_id', '=', $md)-
>groupBy('pivot_parent');
})->first();

Trouble converting an SQL query to Eloquent

Trying to get this query to work in eloquent
A user can be in multiple teams however I want to generate a list of users NOT in a specific team. The following SQL query works if executed directly but would like to make it cleaner by converting it to eloquent
SELECT * FROM users LEFT JOIN team_members ON team_members.member_id = users.id WHERE NOT EXISTS ( SELECT * FROM team_members WHERE team_members.member_id = users.id AND team_members.team_id = $team_id )
This should provide a list of all the users that are not members of team $team_id
This is a guess ad you do not give much info on your Eloqent models but here is a hint of where to go:
User::doesnthave('teamMembers', function($builder) use($team_id){
return $builder->where('team_members.team_id');
});
That is assuming you have a "User" model with a "teamMembers" relationship setup on it
You may have a closer look in the Laravel docs for doesntHave
Laravel 5.8
Let's assume you have model name "User.php"
& there is method name "teamMembers" in it.
Basic
$users = User::doesntHave('teamMembers')->get();
Advance
use Illuminate\Database\Eloquent\Builder;
$users = User::whereDoesntHave('teamMembers', function (Builder $query) {
$query->where('id', '=', {your_value});
})->get();
You can find details description in this link >>
https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-absence
Laravel 5.2
Example:
DB::table('users')
->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
->get();
Check this link for advance where clause:
https://laravel.com/docs/5.2/queries#advanced-where-clauses
You can use below example
$list = User::leftJoin('users', 'users.id', '=', 'team_members.member_id')
->whereNotExists(function ($query) use ($team_id) {
$query->from('team_members')
->whereRaw('team_members.member_id = users.id')
->where('team_members.team_id', '=', $team_id);
})
->get();

Eloquent Get Models based on fields in related tables

I have multiple Models related to my User model(eg: profiles, addresses, orders,...etc)
I want to get all the users that were updated in the past 24 hours, based on the update_at field in each of the related tables accordingly.
I have found the following if u have one related table, but in my case I have more than 3 tables that I need to check:
$users = User::with('orders')
->where('updated_at', $valueA)
->whereHas('orders', function($query)
{
$query->where('updated_at', $valueB);
})->get();
I hope someone can help me to know how to apply this for multiple where clauses n=on multiple related tables.
Try the below code,
$users = User::with(['profiles', 'addresses', 'orders'])
->whereDate('updated_at','>', $yesterdayDate)
->orWhereHas('orders', function($query) use ($yesterdayDate){
$query->whereDate('updated_at','>', $yesterdayDate);
})->orWhereHas('addresses', function($query) use ($yesterdayDate) {
$query->where('updated_at','>', $yesterdayDate);
})->orWhereHas('profiles', function($query) use ($yesterdayDate){
$query->where('updated_at','>', $yesterdayDate);
})->get();
If you have direct relation from users to all models like orders, profiles, addresses etc then you can try this.
$valueA = $time // whatever time you want
$users = User::
where('updated_at', $valueA)
->whereHas('orders', function($query) use ($valueA)
{
$query->where('updated_at', $valueA);
})
with('orders')
->whereHas('profiles', function($query) use ($valueA)
{
$query->where('updated_at', $valueA);
})
with('profiles')
->whereHas('addresses', function($query) use ($valueA)
{
$query->where('updated_at', $valueA);
})
with('addresses')
->get();
Thank you.

Get Model where relationship = id

Would love to know how other people are achieving the following?
Tables:
teams
teams_users (pivot many teams, many users)
users
What i am trying to achieve
$teams->user->where('user_id', $id)->get();
however i am having to run a loop, and create another method on the team model to pluck(id, name)
// foreach ($teams as $team) {
// # code...
// dump($team->getUserIdsAttribute());
// }
Do you know a better way?
If you are trying to get all teams with a specific a user id. Try
$teams = Team::with(['users' => function ($query) use ($id) {
$query->where('id', '=', $id);
}])->get();
Or through the user
$user = User::with('teams')->find($id);
This is assuming you already defined the belongsToMany() relationship in each model.
Maybe you will like to do it in the more traditional way
use Illuminate\Database\Eloquent\Builder;
$team = Team::whereHas('user',function(Builder $query) use ($id){
$query->where( 'user_id' , $id );
})->get();

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.

Resources