Using trait hasAssignees for Select in form

Hi all, I have a Trait called HasAssignees
public function assignees()
{
return $this->morphToMany(User::class, 'assignable')
->withTimestamps();
}

public function assignTo(User $user)
{
$this->assignees()->syncWithoutDetaching([$user->id]);
}
etc...
public function assignees()
{
return $this->morphToMany(User::class, 'assignable')
->withTimestamps();
}

public function assignTo(User $user)
{
$this->assignees()->syncWithoutDetaching([$user->id]);
}
etc...
Which i want to use to populate a SelectField in a form with list of users which would be assigned to a model (task, Booking etc). This is the model
class Assignee extends Model
{
protected $fillable = ['user_id'];

public function user()
{
return $this->belongsTo(User::class);
}
}
class Assignee extends Model
{
protected $fillable = ['user_id'];

public function user()
{
return $this->belongsTo(User::class);
}
}
and the db structure for the trait
Schema::create('assignees', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('assignable_id');
$table->string('assignable_type');
$table->timestamps();

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
Schema::create('assignees', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('assignable_id');
$table->string('assignable_type');
$table->timestamps();

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
I "think" the answer lies in the self:: but i am a bit stuck can anyone assist how i can show a select field to display the assignees of that record? Thanks in advance!!
3 Replies
nostrodamned
nostrodamnedOP2y ago
I think i may be overengineering this - just simple has many relationship on model
Patrick Boivin
Hi @cvc_web, I'm not sure but something looks off about the morphToMany()... are you able to use the relationship? To your question, you can use a query for the options of a select field, something like this:
Select::make('user_id')
->options(fn ($record) => $record->assignees->pluck('name', 'id'))
Select::make('user_id')
->options(fn ($record) => $record->assignees->pluck('name', 'id'))
This would only work on edit obviously...
nostrodamned
nostrodamnedOP2y ago
Hi yes, I think i got in my own brain trying to use a trait! I eventually went for Pivot Table and one to Many relationship. but thanks for the help anyway - it did work on the edit - but adding became more of a hell
Want results from more Discord servers?
Add your server