Support the ongoing development of Laravel.io →
Eloquent Laravel Blade
Last updated by @ajax30 3 weeks ago.
0

In your current code, the issue lies in the condition when($filter !== 'all') inside the query builder. When the selected filter is "All comments", the condition evaluates to true, and the where clause is applied to filter the comments by approval status. However, since you want to display all comments in this case, you need to modify the condition to include the "All comments" filter as well.

Here's an updated version of the code that should address the issue:

$comments = Comment::orderBy('id', 'desc')
    ->when($filter !== 'all', function ($query) use ($filter) {
        return $query->where('approved', $filter);
    }, function ($query) {
        // Add a fallback condition to include all comments when $filter === 'all'
    })
    ->paginate($per_page)->onEachSide(1);

This modification adds a fallback function to the when method, which will be executed when the condition evaluates to false. In this case, it doesn't apply any additional filtering, effectively including all comments in the result.

By making this change, the comments will be correctly filtered when "Unapproved" or "Approved" is selected, and all comments will be shown when "All comments" is selected.

Additionally, make sure that the value attribute of the "All comments" option in the select box is set to "all" so that it matches the value used in the condition.

<option value="all">All comments</option>

With these adjustments, the issue should be resolved, and you should be able to display the desired comments based on the selected filter option.

Or you can reference these links to get more information: https://laravel.com/docs/8.x/controllers https://stackoverflow.com/questions/51223265/how-to-show-comments-uno online-and-replycomments-in-laravel

0

@alanrodgers I did this:

$comments = Comment::orderBy('id', 'desc')
    ->when($filter !== 'all', function ($query) use ($filter) {
        return $query->where('approved', $filter);
    }, function ($query) {
     // Get approved and approved comments
      return $query->where('approved', 1)->orWhere('approved', 0);
    })
    ->paginate($per_page)->onEachSide(1);

It does not work. What would be a working alternative?

Last updated by @ajax30 3 weeks ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Razvan ajax30 Joined 2 Oct 2021

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.