Hello developers! In this guide, we'll see how to add Flatpickr datetime in the laravel 10. Laravel 10 application by integrating Flatpickr with DateTime functionality and displaying human-friendly dates. Flatpickr is a versatile date and time picker library that brings simplicity and elegance to your application's date selection.
Flatpickr is a lightweight and powerful datetime picker. Lean, UX-driven, and extensible, yet it doesn't depend on any libraries.
Laravel 10 Add Flatpickr Datetime
Include Flatpickr via CDN in your Blade layout file (e.g., resources/views/layouts/app.blade.php
) within the <head>
section:
<!-- Add this to the head section of your layout file -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
Create a new Blade view (e.g., resources/views/flatpickr.blade.php
). This view will contain a form with a DateTime input field:
@extends('layouts.app')
@section('content')
<div class="container">
<form action="{{ route('save.datetime') }}" method="POST">
@csrf
<label for="datetimepicker">Select a Date and Time:</label>
<input type="text" id="datetimepicker" name="selected_datetime">
<button type="submit">Save DateTime</button>
</form>
</div>
<script>
// Initialize Flatpickr with DateTime functionality
flatpickr("#datetimepicker", {
enableTime: true, // Enable time selection
dateFormat: "Y-m-d H:i", // Customize the date and time format as needed
});
</script>
@endsection
Human-friendly Dates
<script>
// Initialize Flatpickr with DateTime functionality
flatpickr("#datetimepicker", {
altInput: true,
altFormat: "F j, Y",
dateFormat: "Y-m-d",
});
</script>
Generate a controller using the Artisan command:
php artisan make:controller FlatpickrController
In your FlatpickrController.php
, add methods to show the view and save the selected DateTime:
use Illuminate\Http\Request;
class FlatpickrController extends Controller
{
public function showForm()
{
return view('flatpickr');
}
public function saveDateTime(Request $request)
{
// Handle saving the selected DateTime logic
// $request->input('selected_datetime') contains the selected DateTime
}
}
Add the corresponding routes in web.php
:
use App\Http\Controllers\FlatpickrController;
Route::get('/flatpickr', [FlatpickrController::class, 'showForm']);
Route::post('/save-datetime', [FlatpickrController::class, 'saveDateTime'])->name('save.datetime');
Run your Laravel application:
php artisan serve
You might also like:
- Read Also: Laravel 10 Convert UTC Time to Local Time
- Read Also: Laravel 10 Filter Datatable with Dropdown
- Read Also: How to Display Tooltip in Bootstrap Vue JS
- Read Also: How To Add Bootstrap 5 Modal In Laravel 10