Rubberduck1337106092
Rubberduck1337106092

Reputation: 1344

Sorting users through relation in laravel

i want to sort the users through voornaam(firstname). but im getting the data via a relation.

How do i make my query so that, the relation users are sorted by firstname by alphabet

my function:

public function sortfirstname($id) {
    $ingeschrevenspelers = UserToernooi::with('users')->where('toernooiid', '=', $id)->get()->all();
 //This query ^^


    $toernooi = Toernooi::findOrFail($id);

    dd($ingeschrevenspelers);
    return view('adminfeatures.generatespelerslijst', compact('ingeschrevenspelers', 'toernooi'));
}

What i want to sort enter image description here

any help is appreciated

thanks in advance

Upvotes: 0

Views: 47

Answers (4)

Max Gaurav
Max Gaurav

Reputation: 1913

Don't fire all() function at the end thus obtaining a Collection instance of result

//query without the all function
$ingeschrevenspelers = UserToernooi::with('users')->where('toernooiid', '=', $id)->get();

//
$ingeschrevenspelers = $ingeschrevenspelers->sortBy('users.firstname');

Upvotes: 1

Akshay Vaghasiya
Akshay Vaghasiya

Reputation: 1637

$ingeschrevenspelers = UserToernooi::with(['users' => function($query){
    $query->orderBy('voornaam', 'asc');
}])->where('toernooiid', '=', $id)->get()->all();

Upvotes: 0

Mosufy
Mosufy

Reputation: 151

An alternative to Jordy Groote's answer if you do not want to modify the Model class itself, you can query it with a closure.

$ingeschrevenspelers = UserToernooi::with(['users' => function($q) {  
    $q->orderBy('voornaam', 'asc');
}])->where('toernooiid', '=', $id)->get()->all();

Reference: https://laravel.com/docs/5.3/eloquent-relationships#constraining-eager-loads

Sidenote: I don't think you need a ->all() when you already did a ->get()

Upvotes: 1

Pistachio
Pistachio

Reputation: 1652

Writing code in your own language doesn't make it very easy for other developers to understand your code.

That being said, you can try the orderBy() method on your relationship

In your model where you define the relationship:

public function relationship() 
{
    return $this->belongsTo(SomeClass::class)->orderBy('name', 'DESC');
}

Upvotes: 2

Related Questions