samedi 2 juillet 2016

Call Magic methods in Eloquent laravel 5.2

i try use __call magic method for make dynamic method in laravel Eloquent. i have blog and blog_translations table and TITLE,CONTENT must be load from blog_translations table .

public function translations($lang = null)
{
    if(empty($lang)) {
        if (!empty(Lang::getLocale())) {
            $language = Lang::getLocale();
        } else {
            $language = Config::get('app.fallback_locale');
        }
    }else{
        $language = $lang;
    }
    return $this->hasMany(Blog_Translation::class)->where('locale', $language);
}

public function __call($method,$arg)
{
    $filed = str_replace('get','',$method);
    if(sizeof($arg) >= 1){
        $lang = $arg[0];
    }else {
        $lang = '';
    }
    return $this->translations($lang)->where('name',$filed)->first()->text;
}

in controller :

    $blog   = Blog::find(1);
    return $blog->getTITLE();

error :

Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$id

with remove __call function relationship work good.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire