Carbon is probably the most effective way to handle DateTime strings flawlessly and implement PHP code that everybody can easily extend or debug.
1 |
echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago' |
In the following example, I would like to demonstrate how you can filter a collection in Laravel by using Carbon. As you can see, the below example will simply return all People who have registered in the past two weeks.
1 2 3 4 5 6 7 |
$from = Carbon::now()->subWeeks(2); $to = Carbon::now(); $people = (new People()) ->whereBetween('registered_at', [$from, $to]) ->orderBy('registered_at', 'desc') ->get(); |
The method subWeeks() will do all the work for you and return a valid DateTime string from 14 days ago which can be used for the whereBetween query method. If you prefer using days, you can simply use subDays() instead.
One possible use case could be a front-end controller that handles AJAX requests.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php namespace Your\Plugin\Controllers\Frontend; use Illuminate\Routing\Controller; use Your\Plugin\Models\People; use Response; use Carbon\Carbon; class Work extends Controller { public function index($weeks) { try { $from = Carbon::now()->subWeeks($weeks); $to = Carbon::now(); $people = (new People()) ->whereBetween('registered_at', [$from, $to]) ->orderBy('registered_at', 'desc') ->get() ->toArray(); return Response::json($people, 200)->send(); } catch (\Exception $ex) { $ex->getMessage(); } } } |