Laravel | Benutzermodel erweitern

Laravel bietet mit Eloquent ORM ein leistungsfähiges Datenbank-Framework.

Mit Hilfe von Modellen werden die Datenbankobjekte (z. B. Benutzer) definiert. Diese Objekte können dabei einfach durch zusätzliche Felder erweitert werden.

Im nachfolgenden Beispiel wollen wir das vorhandene Objekt

User
User einer initialen Laravel-Installation durch ein Feld
username
username erweitern.

Inhaltsverzeichnis [Anzeigen]

Neues Feld den Benutzermodel hinzufügen

Erstellen eines Datenbank-Migrationsskriptes, das unser gewünschtes Feld zur Tabelle

users
users hinzufügt.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
php artisan make:migration add_column_username_to_users_table --table users
php artisan make:migration add_column_username_to_users_table --table users
php artisan make:migration add_column_username_to_users_table --table users

Hinzufügen des Felder Username in der neu erstellten Datei. Dies liegt unter

database/migrations.
database/migrations.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('username')->nullable();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('username');
});
}
public function up() { Schema::table('users', function (Blueprint $table) { $table->string('username')->nullable(); }); } public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('username'); }); }
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('username')->nullable();
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('username');
        });
    }

Hinzufügen des Feldes Username im Datenbankmodel User in der Datei app\Models\User.php

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
protected $fillable = [
'name',
'email',
'password',
'username'
];
protected $fillable = [ 'name', 'email', 'password', 'username' ];
    protected $fillable = [
        'name',
        'email',
        'password',
        'username'
    ];

Datenbank aktualisieren.

Dieser Schritt entfernt alle Tabellen und erstellt sie neu. Dadurch gehen natürlich alle bereits vorhandenen Daten verloren!

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
❯ php artisan migrate:fresh --seed
Dropped all tables successfully.
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (2,326.47ms)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (1,789.28ms)
Migrating: 2014_10_12_200000_add_two_factor_columns_to_users_table
Migrated: 2014_10_12_200000_add_two_factor_columns_to_users_table (1,010.74ms)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated: 2019_08_19_000000_create_failed_jobs_table (2,399.99ms)
Migrating: 2019_12_14_000001_create_personal_access_tokens_table
Migrated: 2019_12_14_000001_create_personal_access_tokens_table (2,313.60ms)
Migrating: 2021_06_19_085151_create_sessions_table
Migrated: 2021_06_19_085151_create_sessions_table (5,279.76ms)
Migrating: 2021_06_19_102316_add_username_to_users_table
Migrated: 2021_06_19_102316_add_username_to_users_table (432.59ms)
Database seeding completed successfully.
❯ php artisan migrate:fresh --seed Dropped all tables successfully. Migration table created successfully. Migrating: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table (2,326.47ms) Migrating: 2014_10_12_100000_create_password_resets_table Migrated: 2014_10_12_100000_create_password_resets_table (1,789.28ms) Migrating: 2014_10_12_200000_add_two_factor_columns_to_users_table Migrated: 2014_10_12_200000_add_two_factor_columns_to_users_table (1,010.74ms) Migrating: 2019_08_19_000000_create_failed_jobs_table Migrated: 2019_08_19_000000_create_failed_jobs_table (2,399.99ms) Migrating: 2019_12_14_000001_create_personal_access_tokens_table Migrated: 2019_12_14_000001_create_personal_access_tokens_table (2,313.60ms) Migrating: 2021_06_19_085151_create_sessions_table Migrated: 2021_06_19_085151_create_sessions_table (5,279.76ms) Migrating: 2021_06_19_102316_add_username_to_users_table Migrated: 2021_06_19_102316_add_username_to_users_table (432.59ms) Database seeding completed successfully.
❯ php artisan migrate:fresh --seed
Dropped all tables successfully.
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (2,326.47ms)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (1,789.28ms)
Migrating: 2014_10_12_200000_add_two_factor_columns_to_users_table
Migrated:  2014_10_12_200000_add_two_factor_columns_to_users_table (1,010.74ms)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated:  2019_08_19_000000_create_failed_jobs_table (2,399.99ms)
Migrating: 2019_12_14_000001_create_personal_access_tokens_table
Migrated:  2019_12_14_000001_create_personal_access_tokens_table (2,313.60ms)
Migrating: 2021_06_19_085151_create_sessions_table
Migrated:  2021_06_19_085151_create_sessions_table (5,279.76ms)
Migrating: 2021_06_19_102316_add_username_to_users_table
Migrated:  2021_06_19_102316_add_username_to_users_table (432.59ms)
Database seeding completed successfully.

Erweitern der Frontend Views

Hinzufügen des Feldes Username in der Datei resources\views\profile\edit.blade.php

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<x-slot name="form">
...
<!-- Email -->
...
<!-- column username -->
<div class="form-group row">
<label for="username" class="col-md-4 col-form-label text-md-right">{{ __('Benutzername') }}</label>
<div class="col-md-6">
<input id="username"
type="text"
class="form-control @error('username') is-invalid @enderror" name="email"
value="{{ old('email') ?? auth()->user()->email }}"
required autocomplete="email" autofocus>
@error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
</x-slot>
<x-slot name="form"> ... <!-- Email --> ... <!-- column username --> <div class="form-group row"> <label for="username" class="col-md-4 col-form-label text-md-right">{{ __('Benutzername') }}</label> <div class="col-md-6"> <input id="username" type="text" class="form-control @error('username') is-invalid @enderror" name="email" value="{{ old('email') ?? auth()->user()->email }}" required autocomplete="email" autofocus> @error('username') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> </x-slot>
<x-slot name="form">
   ...

   <!-- Email -->
      ...


   <!-- column username -->
   <div class="form-group row">
      <label for="username" class="col-md-4 col-form-label text-md-right">{{ __('Benutzername') }}</label>

      <div class="col-md-6">
         <input id="username" 
               type="text" 
               class="form-control @error('username') is-invalid @enderror" name="email" 
               value="{{ old('email') ?? auth()->user()->email }}" 
               required autocomplete="email" autofocus>

          @error('username')
          <span class="invalid-feedback" role="alert">
             <strong>{{ $message }}</strong>
          </span>
          @enderror
       </div>
    </div>
 </x-slot>

Anpassen des Controllers

Wir passen die PHP Komponente UpdateUserProfileInformation an, so das die neuen Werte gespeichert werden

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
app\Actions\Fortify\UpdateUserProfileInformation.php
app\Actions\Fortify\UpdateUserProfileInformation.php
app\Actions\Fortify\UpdateUserProfileInformation.php
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public function update($user, array $input)
{
...
if ($input['email'] !== $user->email &&
$user instanceof MustVerifyEmail) {
$this->updateVerifiedUser($user, $input);
} else {
$user->forceFill([
'name' => $input['name'],
'email' => $input['email'],
'username' => $input['username'],
])->save();
}
}
public function update(user,arrayinput) { ... if (input[email]!==user->email && $user instanceof MustVerifyEmail) { this>updateVerifiedUser(user, $input); } else { user>forceFill([name=>input['name'], 'email' => input[email],username=>input['username'], ])->save(); } }
    public function update($user, array $input)
    {
        ...

        if ($input['email'] !== $user->email &&
            $user instanceof MustVerifyEmail) {
            $this->updateVerifiedUser($user, $input);
        } else {
            $user->forceFill([
                'name' => $input['name'],
                'email' => $input['email'],
                'username' => $input['username'],
            ])->save();
        }
    }