Skip to content

Instantly share code, notes, and snippets.

@ok200paul
Created December 7, 2020 00:30
Show Gist options
  • Save ok200paul/2d68e44161ec27de357803d4ac26abf3 to your computer and use it in GitHub Desktop.
Save ok200paul/2d68e44161ec27de357803d4ac26abf3 to your computer and use it in GitHub Desktop.
Loading dates into controller URLs
<?php
/**
* Show the page for a given date (eg the URL would be /my-tasks/2020-12-07)
*/
public function showDashboardForGivenDate($date)
{
$startDate = Carbon::parse($date); // Carbon Object
$dateIsValid = $startDate->toDateString() === $date; // bool
/**
* They've sent in gobbledegook. Redirect to today and re-render.
*/
if (!$dateIsValid) {
return Redirect::to('/my-tasks/' . now()->toDateString()); // ..or whatever date eg start of week, now()->weekday(0)->toDateString()
}
/**
* Set some meta for the view, so we can play around with dates in links
*/
$endDate = $startDate->addDays(7);
$data['datesInView'] = [
'startDate' => $startDate,
'endDate' => $endDate,
];
/**
* Get the data.
* Note that eloquent is cool passing Carbon objects into it
*/
$data['orders'] = DealOrder::whereBetween('created_at', [$startDate->startOfDay(), $endDate->endOfDay()])->get();
return view('app.view', $data);
}
<div>
<a href="/my-tasks/{{ $datesInView['startDate']->subdays(7)->toDateString() }}">Back 7 days</a>
<a href="/my-tasks/{{ $datesInView['startDate']->addDays(7)->toDateString() }}">Forward 7 days</a>
</div>
<?php
// ..
Route::get('/my-tasks/{date}', 'WhateverController@showDashboardForGivenDate');
// ..
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment