Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

This can be cleaned up a lot...

Banner::isVisible()->startDate($today)->endDate($today)->categories()->byCategoryId($category->id)->get();

All those wheres could be thrown into query scopes so you can create more readable code. To access inside the categories relationship, you need the parens with creates a query builder. I don't have your data to test, but this should help you.

0

Thank you rocketpastsix for your advice, I will read more about those wheres and take it in count.

I received solution from users in laracast forum, so I share here, because it may helps somebody else.

Correct query in eloquent way is:

$banners = Banner::where('visible', 1)
    ->where('visible', 1)
    ->where('up_at','<=', $today)
    ->where('down_at','>=', $today)->get();
    ->with('categories')
    ->whereHas('categories', function($query) use ($categoryId)  {
        $query->where('id', $categoryId);
    })->get();
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.