Courses

Livewire 3 for Beginners with Laravel 12 Starter Kit

Date Picker with due_date Field

Summary of this lesson:
- Adding a `due_date` field to the database and model
- Implementing validation and saving/updating the `due_date` in the Livewire component
- Adding a date input field in the form using the native browser date picker
- Displaying the `due_date` in the tasks table with formatted output

Now, let's try to add one more field to our form and database: due_date with a date picker.


Prepare Database/Livewire Component

I will just show you the code without any comments. These are Laravel fundamentals, I'm sure you know them.

Migration:

php artisan make:migration add_due_date_to_tasks_table
Schema::table('tasks', function (Blueprint $table) {
$table->date('due_date')->nullable();
});

Then, we run:

php artisan migrate

Adding to Model fillables:

app/Models/Task.php:

class Task extends Model
{
use HasFactory;
 
protected $fillable = [
'name',
'is_completed',
'due_date',
];
 
protected function casts(): array
{
return [
'is_completed' => 'boolean',
'due_date' => 'date'
];
}
}

Validation rules and saving/updating date:

app/Livewire/Tasks/Create.php:

class Create extends Component
{
#[Validate('required|string|max:255')]
public string $name = '';
 
#[Validate('nullable|date')]
public null|string $due_date = null;
 
public function save(): void
{
$this->validate();
 
Task::create([
'name' => $this->name,
'due_date' => $this->due_date,
]);
 
session()->flash('success', 'Task successfully created.');
 
$this->redirectRoute('tasks.index', navigate: true);
}
 
// ...
}

app/Livewire/Tasks/Edit.php:

class Edit extends Component
{
#[Validate('required|string|max:255')]
public string $name;
 
#[Validate('nullable|boolean')]
public bool $is_completed;
 
#[Validate('nullable|date')]
public null|string $due_date = null;
 
public Task $task;
 
public function mount(Task $task): void
{
$this->task = $task;
$this->name = $task->name;
$this->is_completed = $task->is_completed;
$this->due_date = $task->due_date?->format('Y-m-d');
}
 
public function save(): void
{
$this->validate();
 
$this->task->update([
'name' => $this->name,
'is_completed' => $this->is_completed,
'due_date' => $this->due_date,
]);
 
session()->flash('success', 'Task successfully updated.');
 
$this->redirectRoute('tasks.index', navigate: true);
}
 
// ...
}

Ok, the back end is ready. It's time to...

The full lesson is only for Premium Members.
Want to access all 19 lessons of this course? (91 min read)

You also get:

  • 73 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord