Why not just use the MySQL standard YYYY-MM-DD in the database and format it in your blade to support your needs?
Date formating for database storage.
So I was wondering, I have a simple form that is used to add new 'Issues/Improvements' to one of my projects and one of the fields it's of course a "Deadline" date field. I used the Daterangepicker js library cause I find it nice and easy to use even though a normal Html input field did the work just right.
So as you very well know SQL dates are stored in the format Y-m-d. So I had to somehow alter the 'deadline' in order to be able to be stored (my format was DD/MM/YYYY). Came up with two ways of doing it.
- Using a Mutator in my model
``` function setDeadlineAttribute($date) {
return $this->attributes['deadline'] = Carbon::parse($date);
}
```
- In my IssuesController@store (abstract) I create 2 new variables store the date and use Carbon to format it.
``` public function store(IssueRequest $request) { $input = $request->input('deadline'); $date = Carbon::parse($input)->format('Y/m/d');
$issue = Issue::create([
'name' => $request->input('name'),
'deadline' => $date,
'priority' => $request->input('priority'),
'description' => $request->input('description'),
]);
```
As mentioned above both work but I can't but feel that the mutator option is the way to go. Maybe there is an even better/cleaner way to do this that you follow (better coding standards), I don't know that is why I am asking for your personal views on the matter!
Many thanks!
I agree. Store dates in the native yyyy-mm-dd format. If you don't, you'll lose a lot of date calculation functionality and have to write some queries manually.
Just add deadline to the protected $dates array and it will convert it to carbon. Then all you need to do is format it when displaying. https://laravel.com/docs/5.7/eloquent-mutators#date-mutators
Please or to participate in this conversation.