I had forgotten how to do this and had to remember the other day, so in case anybody else stumbles on this post, this is how I did it.
Let's assume:
Model Students belongs to model Classroom
If you are using YAML to do your relation field in a form...
you would have something like:
models/student/fields.yaml
fields:
classroom:
label: 'Classroom Student bleongs to'
nameFrom: class_name
span: auto
type: relation
scope: sortedClassrooms
other_fields.....
The trick here is the SCOPE
We set this scope on our classroom model:
class Calssrom extends model
{
// ... all your code with rules and whatnot
public function scopeSortedClassrooms($query){
return $query->orderBy('class_name', 'ASC');
}
That should do the trick.
(An observation, scopes allow you to do all sorts of cool things, like, if you have a "is_published" flag, you could filter only the published classrooms, or add any other logic to your relation)