Skip to content

Instantly share code, notes, and snippets.

@webrobert
Last active June 9, 2024 01:45
Show Gist options
  • Save webrobert/76af2ad4bb60fd9268064ba4a05e9f9f to your computer and use it in GitHub Desktop.
Save webrobert/76af2ad4bb60fd9268064ba4a05e9f9f to your computer and use it in GitHub Desktop.
A simple Laravel-Livewire Pikaday date-range picker using Alpine

A simple Laravel-Livewire Pikaday date range picker using Alpine

I wanted a blade component for date-range where the two dates reference one another. There is probably a cleaner way to do this. I'm all ears...

Usage with any two wire:model dates...

<x-date-range-picker class="flex items-end">
  <x-slot name="start_date" wire:model="todo.start_date"></x-slot>
  <x-slot name="end_date"   wire:model="todo.due_date"></x-slot>
</x-date-range-picker>

Naturally, requires momentjs, Pikaday and Livewire

@props([ 'start_date', 'end_date' ])
@php( $sharedClasses = "border-0 border-b p-0 w-40 text-base" )
<div x-data="pikaDateRange($wire)" {{ $attributes }}>
<input x-ref="start" type="text" placeholder="Start date..."
{{ $start_date->attributes->merge(['class' => $sharedClasses ]) }} >
<span class="px-1">to</span>
<input x-ref="end" type="text" placeholder="End date..."
{{ $end_date->attributes->merge(['class' => $sharedClasses ]) }} >
</div>
@pushOnce('scripts')
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('pikaDateRange', (wire) => ({
init() {
let wireModelStart = this.$refs.start.getAttribute('wire:model');
let wireModelEnd = this.$refs.end.getAttribute('wire:model');
let start_date = new Pikaday({...{
field: this.$refs.start,
onSelect: function () {
// set the end_date to one day after start_date
end_date.config({ minDate: window.moment(this.getDate()).add(1, 'days').toDate() });
wire.set( wireModelStart, start_date.toString(), true )
},
}, ...myPikadayConfig()
});
let end_date = new Pikaday({...{
field: this.$refs.end,
onSelect: () => wire.set( wireModelEnd, end_date.toString(), true ),
}, ...myPikadayConfig()
});
start_date.config({ minDate: window.moment().toDate() }); // not before today
}
}))
})
// array for items that share between Pikaday instances
function myPikadayConfig() {
return { toString(date) { return window.moment(date).format('ddd, MMM D, YYYY') } }
}
</script>
@endPushOnce
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment