Laravel return relationship data based on locale

Viewed 142

I have posts table that has related table where I store different translations based on post_id now when I want to return translation data based on user selected locale it says:

mb_strpos(): Argument #1 ($haystack) must be of type string, Closure given

Here is my function

$posts = Post::with('translations', function($q) {
  $q->where('translate_code', app()->getLocale());
})->get();
dd($posts); // returning error above

But if I do this

$posts = Post::with('translations')->get();
dd($posts);

I will get following results

one

Here is translations data details:

two

My question is:

How can I return the one translation that has current locale name only?

3 Answers

If you using callback in with then use array of relations like below. Older version of laravel was working which you mentioned but latest version need array of relations when using callback.

$posts = Post::with(['translations'=> function($q) {
            $q->where('translate_code', app()->getLocale());
        }])->get();

using conditional eager loading should be like this:

$posts = Post::with(['translations'=> function($q) {
  $q->where('translate_code', app()->getLocale());
}])->get();

while the relation name is the key, a closer to get data should be the value for the associative array for 'with' statement.

You can query your relation by using whereHas().

Docs: Laravel Docs Relationships

For example:

$posts = Post::whereHas('translations', function ($query) {
   $query->where('translate_code', 'en');
})->get();

Maybe try to put the app()->getLocale() into a variable first. (after trying this out in tinker, this does seem te return a string, so may passing it by reference might help).

Related