0

I'm trying to make it so that the items pulled from the database are only from the current month, however when I do this using various methods it throws an error (which I can't debug due to a the issue mentioned here). In the code below if I just simply paginate the full results it works fine, but when I start to use query builder methods it gives an error, does anybody have any idea why this error is occurring?

public function index()
{
//        $trades=Trade::paginate(10);

    $currentMonth = date('m');
    $trades = DB::table('trades')->whereMonth('date', $currentMonth)->paginate(10);

//        dd($trades);

    $pastwinners=Winner::paginate(10);
    return view('raffle', compact('pastwinners'), compact('trades'));
}

As you can see above the $pastwinners variable and the first $trades variable provide the proper values, but when I'm trying to select only the ones from this month (using the 'date' field) it seems to break.

Kankuro
  • 305
  • 3
  • 10
  • Does `Trade::` instead of `DB::table('trades')->` work? Does `->get()` instead of `->paginate(10)` work? – Jonas Staudenmeir Jun 07 '18 at 12:14
  • Yea, the top line that is commented out works fine, but I want to be able to select only the items from the current month. – Kankuro Jun 08 '18 at 20:00
  • 1
    Does `Trade::whereMonth('date', $currentMonth)->get();` work? What's the result of `dd(Trade::whereMonth('date', $currentMonth)->toSql());`? – Jonas Staudenmeir Jun 09 '18 at 00:27
  • It works with a dd, but breaks when I render the view, I need to be able to paginate the results. The results from the second line was `select * from 'trades' where month('date') = ?` – Kankuro Jun 09 '18 at 00:37
  • Can you post the view? – Jonas Staudenmeir Jun 09 '18 at 00:41
  • The only thing that breaks it is the `{{ $trades->links() }}` part. I've only used pagination with the method for it, how would I go about limiting it by 10 rows per page? – Kankuro Jun 09 '18 at 01:15
  • Does `$trades->links()` work in the controller? Or does it at least give you a better error message? – Jonas Staudenmeir Jun 09 '18 at 01:18
  • I managed to get it by just replacing get with paginate. Thanks for your help Jonas! – Kankuro Jun 09 '18 at 01:22

1 Answers1

0

Try this one. And if you want to paginate your results, do not forget to add pagination links to your view. Also do not forget the import Carbon in your controller class.

https://laravel.com/docs/5.6/pagination

    public function index()
    {
        $trades = Trade::whereMonth('date' , Carbon::today()->month)->paginate();

        $pastwinners = Winner::all();

        return view('raffle', compact('pastwinners', 'trades');
    }
Tartar
  • 5,149
  • 16
  • 63
  • 104