Is there way to Update foreign field with only using foreign Id field in Laravel

Viewed 28

I have 2 related tables. User and UserCategory table. And two are associated with category id.

User Table Scheme

public function up()
{
    Schema::create('User', function (Blueprint $table) {
        $table->id();
        $table->string('name')->unique()->comment('User Name');
        $table->foreignId('user_category_id')->constrained('UserCategory');
        $table->string('user_category_name');
        $table->foreign('user_category_name')->references('name')->on('UserCategory');
    });
}

UserCategory Table Scheme

public function user_category()
{
    return $this->belongsTo(UserCategory::class, 'user_category_id');
}

User Model

public function user_category()
{
    return $this->belongsTo(UserCategory::class, 'user_category_id');
}

When I Create or Update Model, my ideal is just using category_id, then update with category_name field like this.

My Ideal

\App\Models\User::create([
    'name' => 'Admin User',
    'user_category_id' => 1, // ← not need to specify category_name.
]);

Or do I still have to update Like this?

In the current

\App\Models\User::create([
    'name' => 'Admin User',
    'user_category_id' => 1,
    'user_category_name' => \App\Model\UserCategory::find(1)->name,// ← I don't want to do this. 
]);

Is there a smarter way?

Thank you.

1 Answers

You shouldn't need to store the user_category_name in your users table. You can just query it with your users using User::with('user_category'), then you can access the category name through the relationship.

If you really want to have the category name in your users table, you can use an observer:

php artisan make:observer UserObserver --model=User

Then make a method called creating, something like this:

public function creating(User $user) {
    $user->user_category_name = $user->user_category->name;
}

And don't forget to register your observer inside your EventServiceProvider. With this approach, every time a user is created it will automatically grab the user category name and add it to the record upon insertion.

Related