Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel return relationship data based on locale

Tags:

php

laravel

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?

like image 249
mafortis Avatar asked Jan 01 '26 07:01

mafortis


1 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();
like image 92
John Lobo Avatar answered Jan 03 '26 04:01

John Lobo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!