Select multiple records from SelectInput and iterate when creating
Not sure if this is possible or not, but I have a NotesResource that Creates notes that are linked to a user. What I am wanting to do is to have a Select Input with the multiple() method and when I create that note it then creates that note for each of those users.
I.e
Users selected: Chris, Bob, Jeff.
Note: This is a note that is super important to these three users.
Click save and it creates a seperate note for Chris, Bod and Jeff.
Yes, it's possible to create a note for each selected user using a multiple select input. You can achieve this by iterating over the selected users and creating a note for each one. Here's a basic example using Laravel:
Form with Multiple Select Input:
First, ensure your form has a multiple select input for users. You can use Laravel's Blade syntax to create this:
In your controller, you can handle the form submission by iterating over the selected users and creating a note for each one:
use App\Models\Note;
use Illuminate\Http\Request;
public function store(Request $request)
{
$request->validate([
'users' => 'required|array',
'note' => 'required|string',
]);
$noteContent = $request->input('note');
$userIds = $request->input('users');
foreach ($userIds as $userId) {
Note::create([
'user_id' => $userId,
'content' => $noteContent,
]);
}
return redirect()->back()->with('success', 'Notes created successfully for selected users.');
}
Database Migration for Notes:
Ensure you have a migration for the notes table that includes a user_id foreign key and a content field:
Schema::create('notes', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->text('content');
$table->timestamps();
});
This setup will allow you to select multiple users from the form, and upon submission, it will create a separate note for each selected user with the provided content. Make sure to adjust the routes and models according to your application's structure.
@jigar_dhulla Thank you for your reply. I did find this in tho docs after and came up with this. I hadn't spotted this in the docs till now.
protected function mutateFormDataBeforeCreate(array $data): array
{
// Remove the 'users' key from the data as we're going to handle users separately
unset($data['users']);
return $data;
}
protected function afterCreate(): void
{
// Get the selected users
$selectedUsers = $this->data['users'];
$noteContent = $this->record->notes; // Get the note content
$type = $this->record->type; // Get the type content
foreach ($selectedUsers as $userId) {
// Create a separate note for each herd item
UserNote::create([
'user_id' => $userId,
'notes' => $noteContent,
'type' => $type->value
]);
}
$this->record->delete(); // for some reason it was saving the original array before iterating and saving individual records
}