Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda