1

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 ?

medilies
  • 1,811
  • 1
  • 8
  • 32
  • `->where('locale', $locale)` spells **locale with e** while the return object spells it **local without e** (`"local": "en"`) + In that query you asked for `bn` while the object has `en` – medilies Mar 05 '22 at 12:34

1 Answers1

0
public function tagTranslation(){
    $locale = 'bn'; 

    // below you are drectly returning the value. If there is no item you can make count check or 
    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')
}

You can do something like that (It will check $locale if it does not exits it return 'en'):

public function tagTranslation(){
    $locale = 'bn'; 
    return  $this->hasOne(TagTranslation::class,'tag_id')
                 ->where('locale',$locale ?? 'en')
                 ->select('tag_name','locale');

}
gguney
  • 2,512
  • 1
  • 12
  • 26