Skip to content

Instantly share code, notes, and snippets.

@M-Porter
Last active December 8, 2021 07:24
Show Gist options
  • Save M-Porter/ec3c647898afec8305888b61b179feb4 to your computer and use it in GitHub Desktop.
Save M-Porter/ec3c647898afec8305888b61b179feb4 to your computer and use it in GitHub Desktop.
Laravel 8 Time Zone Select Component
{{-- Simple Usage --}}
<x-time-zone-select name-id="time_zone"/>
{{-- Pre-selecting --}}
<x-time-zone-select name-id="time_zone" value="America/Phoenix"/>
{{-- Selecting based on browser time zone w/ help of AlpineJS --}}
<script src="https://unpkg.com/alpinejs@3.7.0/dist/cdn.min.js" defer></script>
<div x-data="{ selectedTimeZone: Intl.DateTimeFormat().resolvedOptions().timeZone }">
<x-time-zone-select name-id="time_zone" x-model="selectedTimeZone"/>
</div>
<select name="{{ $nameId }}" id="{{ $nameId }}" {{ $attributes }}>
<option value="" {{ !$value ? 'selected' : '' }} disabled hidden>Select a time zone</option>
@foreach($timeZones as $tz)
<option
value="{{ $tz }}"
{{ $value === $tz ? 'selected' : '' }}
>
{{ $tz }}
</option>
@endforeach
</select>
<?php
namespace App\View\Components;
use DateTimeZone;
use Illuminate\View\Component;
class TimeZoneSelect extends Component
{
public string $nameId;
public array $timeZones;
public ?string $value;
/**
* Create a new component instance.
*
* @return void
*/
public function __construct(string $nameId, ?string $value = null)
{
$this->value = $value;
$this->nameId = $nameId;
$this->timeZones = DateTimeZone::listIdentifiers();
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\Contracts\View\View|\Closure|string
*/
public function render()
{
return view('components.time-zone-select');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment