V
V
Vasyl Fomin2016-11-10 14:37:14
Laravel
Vasyl Fomin, 2016-11-10 14:37:14

Request for Elequent with default value. How to do?

There is a site in several languages. What needs to be done is that when a language is specified ($languageId) only the categories of that language are displayed. If not specified, all categories.
I wrote such a scope, but if you do not specify the language, then it does not display anything

public function scopeGetCatLeng ($query, $languageId = '*')
  {
      return $query->where('parent_id', null)->where('language_id', $languageId);
  }

$categories = Category::getCatLeng(1)->get();  // выводит категории с языком 1;
$categories = Category::getCatLeng()->get();  // не выводит категорий вообще;

Maybe I'm not using the * symbol correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2016-11-10
@fomvasss

Um, it's obvious.
1) make NULL the default value
2) add where('language_id') only if this parameter is not NULL
// EDIT

public function scopeGetCatLeng ($query, $languageId = null)
{
   $query->where('parent_id', null);

    if ($languageId !== null) {
        $query->where('language_id', $languageId);
    }

    return $query;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question