0

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

4 Answers 4

2

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');
}
Sign up to request clarification or add additional context in comments.

Comments

1

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');

Comments

1

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()

2 Comments

Thanks this should work also, thank you for helping. but Max was first to answer so his answer is checked as best answer.
lol. Max was the last to answer. But its cool. Max's answer seem simpler if it gives your expected result
0
$ingeschrevenspelers = UserToernooi::with(['users' => function($query){
    $query->orderBy('voornaam', 'asc');
}])->where('toernooiid', '=', $id)->get()->all();

1 Comment

Thanks this should work also, thank you for helping. but Max was first to answer so his answer is checked as best answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.