Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

425
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!