Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

duddy67's avatar

Laravel query builder doesn't work with COALESCE

Hi all, This query works perfectly and return values in both subject and body_html columns.

SELECT translations.id, COALESCE(locale.subject, fallback.subject) as subject, COALESCE(locale.body_html, fallback.body_html) as body_html 
FROM translations 
LEFT JOIN translations AS locale ON locale.translatable_id = translations.translatable_id AND locale.translatable_type = translations.translatable_type AND locale.locale = "fr" 
LEFT JOIN translations AS fallback ON fallback.translatable_id = translations.translatable_id AND fallback.translatable_type = translations.translatable_type AND fallback.locale = "en" 
WHERE translations.translatable_id = 1 AND translations.translatable_type = "App\Models\Email" 
LIMIT 1;

Now the same with the Laravel query builder, (note: the variables used here contain the correct values):

return Translation::selectRaw('translations.id,'.
     'COALESCE(locale.subject, fallback.subject) AS subject,'.
     'COALESCE(locale.body_html, fallback.body_html) AS body_html')
  ->from('translations')
  ->where('translations.translatable_id', $this->id)
  ->where('translations.translatable_type',  get_class($this))
    ->leftJoin('translations AS locale', function ($join) use($locale) { 
          $join->on('locale.translatable_id', 'translations.translatable_id')
                     ->where('locale.translatable_type', 'translations.translatable_type')
                     ->where('locale.locale', $locale);
    })->leftJoin('translations AS fallback', function ($join) {
                $join->on('fallback.translatable_id', 'translations.translatable_id')
                     ->where('fallback.translatable_type', 'translations.translatable_type')
                     ->where('fallback.locale', config('app.fallback_locale'));
})->first();

The id column value is correct but subject and body_html values are empty.

What's wrong with that query ?

0 likes
1 reply

Please or to participate in this conversation.