Ahmad Mobaraki
Ahmad Mobaraki

Reputation: 8160

Laravel get Eloquent relation with default value if relation is not present?

I have a Post model , each post has many translations for example : ru, fr, en - (post_translations table), The working code for getting all posts with a specific translations is like this (e.g. fr):

 $locale = 'fr';
 $posts = Post::with([
        'translations' => function($q) use($locale){
            $q->where('language', $locale);
        }
    ])->get();

But some of $posts does not have fr translation, all posts have en translation .

I want to get all posts with fr translation and for posts which does not have fr , return en translation!

Do I have to do this manually? e.i. loop trough all posts and add en translation to those which does not have fr or there is a laravel way to do this ?

Upvotes: 1

Views: 961

Answers (2)

Simone Cabrino
Simone Cabrino

Reputation: 931

From what you write, I understand that Posts are always written in English and then translated in other languages.

I do not know the use you have to do about this, but I propose you to query all the posts with French and English translations and then filter them while printing them

$locale = 'fr';
$posts = Post::with([
    'translations' => function($q) use($locale){
        $q->where('language', $locale);
        $q->orWhere('language', 'en');
    }
])->get();

Upvotes: 1

Odin Thunder
Odin Thunder

Reputation: 3547

Try this solution to get all fr:

$posts = Post::whereHas('translations', function($q) use($locale){
    $q->where('language', $locale);
})->get();

Hope it help :)

Upvotes: 1

Related Questions