Anyone⁉️
Nov 5, 2026
5
Level 1
Order by and filter by related table attribute with Eloquent
Listing is related to Apartment and Apartment is related to Building.
class Listing extends Model
{
// ... fillable, casts
public function apartment(): BelongsTo
{
return $this->belongsTo(Apartment::class);
}
// ... other relations and functions
}
class Apartment extends Model
{
protected $fillable = [
"unit",
"room_count",
"area",
"floor",
"condition",
"heating",
"furnishings",
"ac",
"phone",
"television",
"internet",
"building_id"
];
public $timestamps = false;
// ... casts
public function building(): BelongsTo
{
return $this->belongsTo(Building::class);
}
public function listings(): HasMany
{
return $this->hasMany(Listing::class);
}
// ... other functions
}
class Building extends Model
{
protected $fillable = [
"city",
"street",
"floor_count",
"elevator",
"parking",
"garage",
"cctv",
"intercom"
];
public $timestamps = false;
// ... casts
public function apartments(): HasMany
{
return $this->hasMany(Apartment::class);
}
// ... other functions
}
I access tables apartments and buildings using with method.
class ListingService
{
use ListingOrderBy, ListingWhere;
private const PAGE_SIZE = 2;
function findAll(string $order)
{
$listings = Listing::query()->with(["apartments", "buildings", "users"]);
return $listings->paginate(self::PAGE_SIZE, pageName: "strana");
}
// ...
}
How do I order by and filter listings by its related table columns? For example, I want to filter listings by city or order listings by area.
trait ListingOrderBy
{
public function orderBy(Builder $listings, string $order)
{
return match ($order) {
"najpopularniji" => $listings->withCount("bookmarks")->orderByDesc("bookmarks_count"),
"veći" => $listings->orderByDesc("bookmarks_count"), // order by $listing->apartment->area
"manji" => $listings->orderByDesc("bookmarks_count"), // order by $listing->apartment->area
"skuplji" => $listings->orderByDesc("price"),
"jeftiniji" => $listings->orderBy("price"),
default => $listings->latest()
};
}
}
trait ListingWhere
{
public function whereCityLike(Builder $listings, array $data)
{
return $listings->when(isset($data["grad"]), function () use ($listings, $data) {
return $listings->whereLike([]); // filter by city from $listing->apartment->building
});
}
Please or to participate in this conversation.
