Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skoobi's avatar
Level 13

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.

Is this possible?

Many thanks

0 likes
4 replies
LaryAI's avatar
Level 58

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:

  1. 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:

    <form action="{{ route('notes.store') }}" method="POST">
        @csrf
        <label for="users">Select Users:</label>
        <select name="users[]" id="users" multiple>
            @foreach($users as $user)
                <option value="{{ $user->id }}">{{ $user->name }}</option>
            @endforeach
        </select>
    
        <label for="note">Note:</label>
        <textarea name="note" id="note" required></textarea>
    
        <button type="submit">Save</button>
    </form>
    
  2. Handling the Form Submission:

    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.');
    }
    
  3. 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.

skoobi's avatar
Level 13

@LaryAI Can you regenerate this to be Filament v3 specific.

jigar_dhulla's avatar
Level 3

May be you can create multiple records in here instead of creating one?

use Illuminate\Database\Eloquent\Model;
 
protected function handleRecordCreation(array $data): Model
{
	$createResult = [];
    foreach ($data['users'] as $userId) {
        $createResult[] = static::getModel()::create([
				'note' => $data['note'],
				'user_id' => $userId
		]);
    }
	return $createResult[0] ?? throw new \Exception('Something went wrong');
}

https://filamentphp.com/docs/3.x/panels/resources/creating-records#customizing-the-creation-process

skoobi's avatar
Level 13

@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
    }
1 like

Please or to participate in this conversation.