next/prev 个月在 laravel 中不起作用

next/prev month is not working in laravel

所以我的这个视图显示了一个 table 和两个按钮 (next/prev)。每个按钮都有一个查询字符串 /?date=next,我使用 request()->has('date').

在我的控制器中捕获了它
<a class="button is-primary is-outlined" href="/?date=prev">Previous</a>
<a class="button is-primary is-outlined" href="/?date=next">Next</a>

用户可以转到下个月,下个月取决于他点击 next/prev 按钮的次数。

最初,我有两种方法。首先,我想我可以使用 $count,只要用户单击 $post->whereMonth('date', $this->count) 中的按钮,它就会递增。其次,简单地使用 Carbon 库,$post->date->addMonth()

在这两种方法中,尽管 next/prev 按钮被点击了多次,但日期保持不变。

第一种方法:

class PostsController extends Controller
{
    protected $count; 

    public function __constructor(){
        $this->count = 0; 
    }

        public function show(Hour $post){
            if(request()->has('date') == 'next'){
                $posts = $post->whereMonth('date', $this->count);
                $this->count++; 
            } else if(request()->has('date') == 'prev'){
                $posts = $post->whereMonth('date', $this->count);
                $this->count++; 
            }

            return view('user.table', compact('posts')); 
        }
}

第二种方法(最喜欢的):

public function show(Hour $post){
    if(request()->has('date') == 'next'){
        $posts = $post->date->addMonth(); 
    } else if(request()->has('date') == 'prev'){
        $posts = $post->date->subMonth(); 
    }

    return view('user.table', compact('posts')); 
}

我看到 Laravel 提供了查询生成器 increment,但这只适用于列,而不适用于变量。

有没有一种方法可以通过记住第二种方法中所示的前一个日期来完成这项工作。

您似乎只想显示日期。在这种情况下,请执行以下操作:

public function show(Hour $post)
{
    $months = request('months', 0);

    if (request('date') === 'next'){
        $posts = $post->date->addMonth();
        $months++;
    } elseif(request('date') === 'prev'){
        $posts = $post->date->subMonth();
        $months--; 
    }


    return view('user.table', compact('posts', 'months')); 
}

并且在视图中:

<a class="button is-primary is-outlined" href="/?date=next&months={{ $months }}">Previous</a>
<a class="button is-primary is-outlined" href="/?date=next&months={{ $months }}">Next</a>