Skip to main content

Date Picker with due_date Field

Premium
2:49

Text Version of the Lesson

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 of our courses? (30 h 09 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.