How To create Crud API in laravel | websolutioncode.com
How To create Crud API in laravel | websolutioncode.com

How To create a RESTful Crud API in laravel

Introduction:

Laravel, a PHP framework, provides powerful tools for building web applications, including RESTful APIs. REST (Representational State Transfer) APIs allow for communication between different systems using HTTP requests. In this tutorial, we will guide you through creating a RESTful API for CRUD (Create, Read, Update, Delete) operations in Laravel, focusing on simplicity and practicality. We’ll cover setting up routes, creating controllers, handling requests, and implementing forms for user interaction.

Prerequisites:

  • Basic understanding of PHP and Laravel.
  • Composer installed on your system.
  • Laravel development environment set up.

Step 1:

Setting Up Laravel Project Firstly, create a new Laravel project by running the following command in your terminal:

composer create-project --prefer-dist laravel/laravel rest-api-crud

Navigate into the project directory:

cd rest-api-crud

Step 2:

Creating Model and Migration Let’s create a model and migration for our CRUD application. For this example, we’ll create a simple “Task” model with fields for title and description.

php artisan make:model Task -m

This command will generate a Task model and its corresponding migration file.

In the migration file (database/migrations/YYYY_MM_DD_create_tasks_table.php), define the schema for the tasks table:

public function up()
{
    Schema::create('tasks', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('description')->nullable();
        $table->timestamps();
    });
}

Then, run the migration to create the tasks table:

php artisan migrate

Step 3:

Creating Controller Now, let’s create a controller to handle CRUD operations for tasks.

php artisan make:controller TaskController --api

This will generate a TaskController with API resource methods for CRUD operations.

Step 4:

Defining Routes Open the routes/api.php file and define the routes for our API endpoints:

use App\Http\Controllers\TaskController;

Route::apiResource('tasks', TaskController::class);

Step 5:

Implementing Controller Methods Open the TaskController.php file (app/Http/Controllers/TaskController.php) and implement the methods for CRUD operations:

<?php

namespace App\Http\Controllers;

use App\Models\Task;
use Illuminate\Http\Request;

class TaskController extends Controller
{
    public function index()
    {
        return Task::all();
    }

    public function store(Request $request)
    {
        return Task::create($request->all());
    }

    public function show($id)
    {
        return Task::findOrFail($id);
    }

    public function update(Request $request, $id)
    {
        $task = Task::findOrFail($id);
        $task->update($request->all());

        return $task;
    }

    public function destroy($id)
    {
        $task = Task::findOrFail($id);
        $task->delete();

        return 204;
    }
}

Step 6:

Testing the API You can now test your API using tools like Postman or cURL. Here are some example requests:

  • GET /api/tasks: Retrieve all tasks.
  • POST /api/tasks: Create a new task.
  • GET /api/tasks/{id}: Retrieve a specific task.
  • PUT /api/tasks/{id}: Update a specific task.
  • DELETE /api/tasks/{id}: Delete a specific task.

Step 7:

Implementing Forms (Optional) To interact with the API through forms, you can create HTML forms in your Laravel views. Here’s a basic example of a form for creating a new task:

<form action="/api/tasks" method="POST">
    @csrf
    <label for="title">Title:</label><br>
    <input type="text" id="title" name="title"><br>
    <label for="description">Description:</label><br>
    <textarea id="description" name="description"></textarea><br><br>
    <button type="submit">Submit</button>
</form>

Conclusion:

In this tutorial, we’ve covered the process of creating a RESTful API for CRUD operations in Laravel. By following these steps, you can efficiently build APIs to interact with your database and handle various operations. Remember to ensure proper validation and security measures when dealing with user input and sensitive data in your applications. Happy coding!

Leave a Reply