In Laravel it is possible to preload the results of the relationships of a given model. So along with this upload, you can also add conditions that will be applied to the relationships that will be uploaded along with your query. This is done through the with
method (Whenever you want to use it, it must be the first method to be called).
In the controller, you can do this:
$with['usuarios'] = function ($query) {
return $query->orderBy('nome');
};
$cliente = Cliente::with($with)->find($id);
Or you can also separate the two, and make a second query for users based on the client query.
$cliente = Cliente::find($id);
$usuarios = $cliente->usuarios()->orderBy('nome')->get();
In the second example, you would have to foreach
in $usuarios
.
Sorting the collection
You can also sort the relationship data after the query completes.
For example, I want to sort my users who are related to a client by name. And then I want to list them again and sort them by update date.
Instead of doing two queries, you can do this:
#controller
$cliente = Cliente::with('usuarios')->find($id);
$ordenadores['nome'] = function ($usuario)
{
return $usuario->nome;
};
$ordenadores['atualizacao'] = function ($usuario)
{
return $usuario->created_at;
};
return view('minha_view', compact('cliente', 'ordenadores'));
Then in the view, you can do this:
#view
@foreach($cliente->usuarios->sortBy($ordenadores['nome']) as $usuario)
@endforeach
@foreach($client->usuarios->sortBy($ordenadores['atualizacao']) as $usuario)
@endforeach
Note : In some cases, it is not necessary to use Callback
in sortBy
. Just pass the field name as the argument of sortBy
, to sort the data in the Collection.
@foreach($client->usuarios->sortBy('created_at') as $usuario)
@endforeach
Tip
Generally, to maintain readability of your model's methods, I suggest you use singular for one-to-one relationships like belongsTo
and hasOne
, and plural for hasMany
or belongsToMany
and related ).