Controller
Tag::with('tagTranslation')->find(5)
Tag Model
function tagTranslation()
{
$locale = Session::get('locale'); // $locale = 'bn';
return $this->hasOne(TagTranslation::class, 'tag_id')
->where('locale', $locale)
->select('tag_name', 'locale')
?? // Or ternary ?:
$this->hasOne(TagTranslation::class, 'tag_id')
->where('locale', 'en')
->select('tag_name', 'locale');
}
If locale='bn'
, then it is showing the expected results like:
{
"id": 5,
"slug": "desktop",
"is_active": 1,
"created_at": "2022-02-25T17:59:18.000000Z",
"updated_at": "2022-03-02T13:42:49.000000Z",
"tag_translations": {
"tag_id": 5,
"tag_name": "ডেস্কটপ",
"local": "en"
}
}
And if I set locale='xyz'
which does not exists in database, then I want to show default data base on locale='en'
like this:
{
"id": 5,
"slug": "desktop",
"is_active": 1,
"created_at": "2022-02-25T17:59:18.000000Z",
"updated_at": "2022-03-02T13:42:49.000000Z",
"tag_translations": {
"tag_id": 5,
"tag_name": "Desktop",
"local": "en"
}
}
But it returns NULL
value like this
{
"id": 5,
"slug": "desktop",
"is_active": 1,
"created_at": "2022-02-25T17:59:18.000000Z",
"updated_at": "2022-03-02T13:42:49.000000Z",
"tag_translations": null
}
How can I solve it ?