Skip to content
Advertisement

laravel 5 get current language id in controller

i’m new to laravel, and i’m wondering how to get the language_id (primary key “id” in database) by current lang_code (a column of language table).

in my language model, i created a function like this :

public function getLang($lang_code = null) {
     $lang_code = App::getLocale();
     return SELF::with($lang_code)->get();
}

in the homeController, i added this line of code:

    $lang = Language::with('getLang');
    echo $lang->id;

Got errors:

at HandleExceptions->handleError('8', 'Undefined property: IlluminateDatabaseEloquentBuilder::$id', '/home/otherraylinux/public_html/starter/app/Http/Controllers/HomeController.php', '52', array('articles' => object(Collection), 'lang' => object(Builder))) in HomeController.php line 52

edit The actual things i want to do is:

$lang = DB::table('languages')->select('id')->where('lang_code', '=', App::getLocale())->get();
echo $lang[0]->id;

edit

What is the problem? And what is the best practice to get the id ? i know the above code should not be good in practice.

Advertisement

Answer

You can use Query scope in laravel 5

Model

public function scopeLangCode($query, $lang_code)
{
    return $query->where('lang_code', $lang_code);
}

Controller

$lang = Language::langCode(App::getLocale())->first();
echo $lang->id;

More details about Query Scope: http://laravel.com/docs/5.0/eloquent#query-scopes

Is this what you are looking for?

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement