A
A
Alexey Sklyarov2020-09-14 14:38:30
Laravel
Alexey Sklyarov, 2020-09-14 14:38:30

Where is the correct place to create an associated element with a user when creating that user?

Perhaps I didn’t formulate the question well, let me explain the essence: I have a user table users and a table with user meta-data (city, gender, age, etc.) users_meta, which is linked to the users table by the user_id field.

users_meta migration class
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersMetaTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users_meta', function (Blueprint $table) {
          $table->unsignedBigInteger('user_id');
          $table->string('occupation')->nullable();
          $table->string('description')->nullable();
          $table->bigInteger('reputation')->default(0);
          $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
          $table->primary(['user_id']);
          $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users_meta');
    }
}


That is, when registering a user, an element associated with the user should be created, which will contain information about him. Where is the best place to do it? I have several more tables that are related to the users table in the same way. At the moment I am creating data in the UserObserver:

UserObserver class

<?php

namespace App\Observers;

use App\Models\User;
use App\Models\Usermeta;

class UserObserver
{
    /**
     * Handle the user "created" event.
     *
     * @param  \App\Models\User  $user
     * @return void
     */
    public function created(User $user)
    {
      Usermeta::create([

      ]);
    }

    /**
     * Handle the user "updated" event.
     *
     * @param  \App\Models\User  $user
     * @return void
     */
    public function updated(User $user)
    {
        //
    }

    /**
     * Handle the user "deleted" event.
     *
     * @param  \App\Models\User  $user
     * @return void
     */
    public function deleted(User $user)
    {
        //
    }

    /**
     * Handle the user "restored" event.
     *
     * @param  \App\Models\User  $user
     * @return void
     */
    public function restored(User $user)
    {
        //
    }

    /**
     * Handle the user "force deleted" event.
     *
     * @param  \App\Models\User  $user
     * @return void
     */
    public function forceDeleted(User $user)
    {
        //
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-09-16
@jazzus

There is nothing better than an observer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question