mercredi 7 juillet 2021

Change default value user creation Schema (migration, Model, Laravel)

Need some help please ,

I have a problem when new user register, the default language is not the same for the website.

I already checked DB and I found that every user get 3 value by default that have relation with language : (language_id , language_code , language_name).

I want to change this default values. I tried many steps but didnt work.

Migration file : create_users_table.php :

 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            //other_columns...
            
            $table->string('language_id')->default(19);
            $table->string('language_code')->default('en');
            $table->string('language_name')->default('English'); 
});

User Model :

 public function language()
    {
        return $this->belongsTo(Language::class);
    }
 public function userLanguage()
    {
        return $this->belongsTo(Language::class, 'language_id')->withDefault();
    }


Middleware SetLocale:

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            $user = Auth::user();
            $lang = $user->userLanguage->code ?? 'en';
        } else {
            if (session()->get('locale')) {
                $lang = session()->get('locale') ?? 'en';
            } else {
                $lang = getSetting()->language->code ?? 'en';
            }
        }

        App::setLocale($lang);
        return $next($request);
    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire