dragonika8
@dragonika8
FrontEnd-Разработчик

Как можно сократить код?

if ($request->building_id == null) {
            $posts = Post::with('buildings')
                ->published()
                ->latest('published_at')
                ->whereCategoryId($request->posts_type)
                ->offset(($request->page - 1) * 6)
                ->take(6)
                ->get(); 
        } else {
            $posts = Post::published()
                ->latest('published_at')
                ->whereCategoryId($request->posts_type)
                ->whereHas('buildings', function ($query) use ($request) {
                    $query->whereId($request->building_id);
                })
                ->offset(($request->page - 1) * 6)
                ->take(6)
                ->get(); 
        };


Можно ли как-нибудь сократить данный код
  • Вопрос задан
  • 117 просмотров
Решения вопроса 2
Lyrium
@Lyrium
Web developer
Вот так, как вариант, можно сократить.

$query = Post::whereCategoryId($request->posts_type);

if (!empty($request->building_id)) {
    $query = $query->with('buildings');
} else {
    $query = $query->whereHas('buildings', function ($query) use ($request) {
            $query->whereId($request->building_id);
        });
}

$posts = $query->published()
    ->latest('published_at')
    ->offset(($request->page - 1) * 6)
    ->take(6)
    ->get();
Ответ написан
Комментировать
@jazzus
Для условий в запросах есть when, разбить на страницы можно с помощью paginate, with как писали в комментариях нужен будет везде иначе что-то с логикой.
$buildingId = $request->input('building_id');

Post::published()
    ->whereCategoryId($request->input('posts_type'))
    ->when($buildingId, function ($query, $buildingId) {

      return $query->whereHas('buildings', function ($query) use($buildingId) {
                  $query->whereId($buildingId);
              });
    })
    ->with('buildings')
    ->latest('published_at')
    ->paginate(6);
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
Sanasol
@Sanasol Куратор тега Laravel
нельзя просто так взять и загуглить ошибку
https://laravel.com/docs/7.x/queries#conditional-c...

А еще необязательно писать все в одну цепочку.
$posts = Post::with('buildings');
$posts->where('1', '=', '2');
$posts->where('3', '=', '4');
$posts->orderBy('id', 'desc');
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы