Courses

React Laravel 12 Starter Kit: CRUD Project

Delete Task and Shadcn Toast Notification

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Adding delete functionality to the tasks table
- Using Shadcn Button component with destructive variant
- Implementing confirmation before delete
- Adding success notifications with Sonner toast component

In this lesson, let's add the Delete button to our table.


Delete Button

Here's what we have in the Controller:

app/Http/Controllers/TaskController.php:

public function destroy(Task $task)
{
$task->delete();
 
return redirect()->route('tasks.index');
}

Since we have Route::resource() here, the React component should fire a DELETE request to the route /tasks/{ID}.

So, first, we define the function inside the React component.

resources/js/pages/Tasks/Index.tsx:

import { Head } from '@inertiajs/react';
import { Head, router } from '@inertiajs/react';
 
// ...
 
export default function Index({ tasks }: { tasks: Task[] }) {
const deleteTask = (id: number) => {
if (confirm('Are you sure?')) {
router.delete(route('tasks.destroy', { id }));
}
};
 
// ...

Then, we need to add a Button to the table that calls the deleteTask() method.

The Shadcn Button component is already installed in the starter kit, so we don't need to run any npx commands. We just need to import it with button variants.

We add a new <TableCell> to our <TableRow>.

resources/js/pages/Tasks/Index.tsx:

import { Button, buttonVariants } from '@/components/ui/button';
 
// ...
 
{tasks.map((task) => (
<TableRow key={task.id}>
<TableCell>{task.name}</TableCell>
<TableCell className={task.is_completed ? 'text-green-600' : 'text-red-700'}>
{task.is_completed ? 'Completed' : 'In Progress'}
</TableCell>
<TableCell className="flex flex-row gap-x-2 text-right"> // [tl! add:start]
<Button variant={'destructive'} className={'cursor-pointer'} onClick={() => deleteTask(task.id)}>
Delete
</Button>
</TableCell> // [tl! add:end]
</TableRow>
))}

Here's the visual result:

Now, see that variant={'destructive'}? To see what other button variants are available, look at...

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

You also get:

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