Ad

Laravel Update Currently Logged In User's Model

- 1 answer

I currently have:

    $lang = Session::get('applocale');
    if ($lang) {
        User::where('id', Auth::user()->id)->update(['language' => $lang]);
    }

Is there a better way to do this through Auth? Perhaps something like Auth::user()->language = $lang or something?


public function switchLang($lang)
{
    if (array_key_exists($lang, Config::get('languages'))) {
        Session::set('applocale', $lang);
        if(Auth::check()) {
            auth()->user()->update(['language' => $lang]);
        }
    }
    return Redirect::back();
}

languages.php (config)

return [
    'en' => 'English',
    'cn' => '中文',
];
Ad

Answer

Instead of:

User::where('id', Auth::user()->id)->update(['language' => $lang]);

you can use:

auth()->user()->update(['language' => $lang]);

However in both cases (your code and mine) you should be sure that user is logged otherwise you might get exception here

Ad
source: stackoverflow.com
Ad