Complete Code for Laravel API Development Project — Build a To-Do List Application with CRUD Operations and User Authentication

Abu Sayed
5 min readMar 5, 2024

--

Learn how to develop a Laravel API for a To-Do List application with CRUD operations and user authentication. This comprehensive guide provides step-by-step instructions, examples, and best practices for creating, reading, updating, and deleting tasks, as well as implementing user authentication using Laravel’s built-in features.

Complete Code for Laravel API Development Project — Build a To-Do List Application with CRUD Operations and User Authentication
Complete Code for Laravel API Development Project

Are you looking to enhance your Laravel skills by building a practical project? In this tutorial, we will guide you through the process of developing a To-Do List application using Laravel’s API capabilities. By the end of this guide, you will have a fully functional API that allows you to perform CRUD operations on tasks and implement user authentication.

Introduction to Laravel API Development

Laravel, a popular PHP framework, offers powerful tools and features for building robust web applications. With its elegant syntax, extensive documentation, and active community, Laravel is an excellent choice for API development.

API, short for Application Programming Interface, allows two software systems to communicate with each other. In the context of web development, an API enables interaction between a client (such as a web or mobile application) and a server.

Building an API with Laravel involves creating endpoints that clients can use to send requests and receive responses. These requests can include creating, reading, updating, or deleting data, commonly known as CRUD operations.

Setting Up the Project

Before we dive into the code, let’s set up our Laravel project. Make sure you have Laravel and Composer installed on your machine. If not, follow the official Laravel documentation for installation instructions.

  1. Open your terminal and navigate to the directory where you want to create your project.
  2. Run the following command to create a new Laravel project:
    composer create-project --prefer-dist laravel/laravel todo-api
  3. Change into the project directory:
    cd todo-api
  4. Generate a new Laravel API resource controller using the following command:
    php artisan make:controller TaskController - api
  5. Next, let’s create the necessary database tables. Edit the `.env` file and configure your database connection.
  6. Run the following command to migrate the tables:
    php artisan migrate

Creating the Task Model and Migration

In our To-Do List application, tasks will be the primary entity. Let’s start by creating a model and migration for the Task.

  1. Generate a new model and migration using the following command:
    php artisan make:model Task -m
  2. Open the newly created migration file located in the database/migrations directory. Inside the up method, define the columns for the tasks table. For example, let’s add the title and completed columns:
    public function up()
    {
    Schema::create('tasks', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->boolean('completed')->default(false);
    $table->timestamps();
    });
    }
  3. Save the file and run the migration command:
    php artisan migrate

Creating API Endpoints for CRUD Operations

With our project set up and the necessary database tables created, we can now proceed to create the API endpoints for performing CRUD operations on tasks.

Retrieving Tasks

Let’s start by creating an endpoint to retrieve all tasks from the database. Open the `TaskController` located in the `app/Http/Controllers` directory.

  1. Import the `Task` model at the top of the file:
    use App\Models\Task;
  2. Add the following method inside the TaskController class:
    public function index()
    {
    $tasks = Task::all();
    return response()->json($tasks);
    }
  3. Save the file and let’s test the endpoint. Start the development server by running the following command:
    php artisan serve
  4. Open your browser and navigate to http://localhost:8000/api/tasks . You should see a JSON response containing all the tasks in the database.

Creating a Task

To create a new task, we need to add another endpoint to our TaskController.

  1. Add the following method inside the TaskController class:
    public function store(Request $request)
    {
    $validatedData = $request->validate([
    'title' => 'required|string|max:255',
    ]);
    $task = Task::create($validatedData);
    return response()->json($task, 201);
    }
  2. Save the file and let’s test the endpoint. Using a tool like Postman or cURL, send a POST request to http://localhost:8000/api/tasks with the following JSON payload:
    {
    "title": "Complete blog post"
    }

You should receive a JSON response containing the newly created task.

Updating a Task

Next, let’s create an endpoint to update an existing task. Add the following method to the TaskController:

public function update(Request $request, Task $task)
{
$validatedData = $request->validate([
'title' => 'required|string|max:255',
'completed' => 'boolean'
]);
$task->update($validatedData);
return response()->json($task);
}

In this code, we are accepting a `Request` object and the `$task` model instance as parameters. The `validate` method is used to validate the request data, ensuring that the `title` field is present and of a string type. Additionally, we allow the `completed` field to be a boolean.

To test the endpoint, send a PUT request to http://localhost:8000/api/tasks/{task_id} with the following JSON payload:

{
"title": "Updated task",
"completed": true
}

Replace {task_id} with the ID of the task you want to update. You should receive a JSON response containing the updated task.

Deleting a Task

Lastly, let’s create an endpoint to delete a task. Add the following method to the TaskController:

public function destroy(Task $task)
{
$task->delete();
return response()->json(null, 204);
}

In this code, we are accepting the $task model instance as a parameter and calling the delete method to remove it from the database. The response is a JSON object with a status code of 204, indicating a successful deletion.

To test the endpoint, send a DELETE request to http://localhost:8000/api/tasks/{task_id}. Replace {task_id} with the ID of the task you want to delete. You should receive a JSON response with a status code of 204.

Implementing User Authentication

To add user authentication to our To-Do List application, we will utilize Laravel’s built-in authentication scaffolding.

  1. Run the following command to generate the authentication scaffolding:
    php artisan make:auth
  2. This command will generate the necessary views, routes, and controllers for user registration, login, and password reset functionality.

Conclusion

Congratulations! You have successfully developed a Laravel API for a To-Do List application with CRUD operations and user authentication. Throughout this guide, we covered the steps to set up the project, create database tables, and implement API endpoints for retrieving, creating, updating, and deleting tasks. Additionally, we explored how to integrate user authentication using Laravel’s built-in features.

By following this tutorial, you have gained valuable experience in Laravel API development, which can be applied to a wide range of web application projects. Remember to continue exploring Laravel’s documentation and the Laravel community for further learning and improvement. Happy coding!

--

--

Abu Sayed

Bangladeshi Full Stack Web Dev, Sys Admin & DevOps Engineer. Skills: Data analysis, SQL, Kubernetes. Python, PHP & Laravel. Me on: bd.linkedin.com/in/imabusayed