vendredi 6 août 2021

Laravel - how to uncheck a checkbox based on result

I currently have some functionality which sends out a newsletter every 7 days containing a list of 10 posts which is preselected with the latest ones available.

Once i hit update it then stores the selected posts into a pivot table called newsletter_post this contains the post that will be sent within the email.

My issue:

When it preselects and i click save and it stores them if i then want to revisit the page and uncheck them and then save it removes them from the pivot but it will automatically check them again due to the preselect when i want there to be none checked if the user has decided they dont want them.

Show page

public function showNewsletter(Partner $partner)
{
    $newsletter = $partner->newsletter;
    if ($newsletter->posts()->exists()) {
        $posts = $newsletter->posts->where('pivot.sent_at', null);
    } else {
        $posts = $partner->posts()
            ->latest()->take(10)->get();
    }

    return view('sections.partner.newsletter-settings', compact('newsletter', 'posts'));
}

Update Method

public function updateNewsletterSettings(Partner $partner)
{
    $newsletter = $partner->newsletter;
    $data = request()->all();

    if (isset($data['posts'])) {
        $posts = Post::whereIn('id', $data['posts'])->get();
        $newsletter->posts()->sync($posts);
    } else {
        $newsletter->posts()->detach();
    }

    session()->flash('success', 'Successfully Updated Newsletter');

    return redirect()->back();
}

Show dropdown

       <x-other.post-checkbox-dropdown :items="$partner->posts()->orderBy('created_at', 'DESC')->get()"
                                                   :model="$posts"></x-other.post-checkbox-dropdown>

Blade Component

<div>
    <div class="checkbox-dropdown">
        <div data-tb-toggle="checkbox-dropdown">Choose Items</div>
        <input type="search" id="post-search" class="form-control" placeholder="Search for posts...">
        <div class="checkbox-items">
            @foreach($items as $item)
                <div class="form-check">
                    <input type="checkbox" class="form-check-input" name="posts[]" id="item_" value="" >
                    <label class="form-check-label" for="item_"></label>
                </div>
            @endforeach
        </div>
    </div>
</div>

Is there a way I can uncheck without it prefilling again?




Aucun commentaire:

Enregistrer un commentaire