Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
Laravel return relationship data based on locale

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?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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();
over 4 years ago · Santiago Trujillo Relatório

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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).

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda