DEV Community

Mehedi Hasan
Mehedi Hasan

Posted on

How to Build a CRUD API with Laravel for Beginners

Laravel is a powerful and elegant PHP framework that makes building web applications easier and more structured. One of the most common uses of Laravel is creating APIs (Application Programming Interfaces) that allow users or other systems to interact with your application. In this tutorial, we will walk through building a simple CRUD (Create, Read, Update, Delete) API with Laravel.

Prerequisites

Before we start, make sure you have the following installed:

If you don’t have Laravel installed yet, you can set it up by running:

composer create-project --prefer-dist laravel/laravel crud-api
Enter fullscreen mode Exit fullscreen mode

Once installed, navigate to the newly created project folder:

cd crud-api
Enter fullscreen mode Exit fullscreen mode

Step 1: Set Up the Database

First, you need to configure your database. In this guide, we’ll use MySQL. Open the .env file and update the following lines with your database credentials:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=crud_api
DB_USERNAME=root
DB_PASSWORD=your_password
Enter fullscreen mode Exit fullscreen mode

Now, create a MySQL database with the name crud_api.

Step 2: Create a Model and Migration

Laravel's Eloquent ORM allows you to interact with your database efficiently. To create a model and migration for your API, run the following Artisan command:

php artisan make:model Post -m
Enter fullscreen mode Exit fullscreen mode

This will generate a Post model in the app/Models directory and a migration file in the database/migrations directory.

Open the migration file (database/migrations/xxxx_xx_xx_create_posts_table.php) and define the columns for the posts table. We’ll create a simple table with fields for title and content:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('content');
        $table->timestamps();
    });
}
Enter fullscreen mode Exit fullscreen mode

Run the migration to create the posts table in your database:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 3: Create API Routes

Laravel provides a straightforward way to define routes for your API. Open the routes/api.php file and define your CRUD routes for the Post resource:

use App\Http\Controllers\PostController;

Route::apiResource('posts', PostController::class);
Enter fullscreen mode Exit fullscreen mode

This will automatically register routes for the index, show, store, update, and destroy methods.

Step 4: Create a Controller

Next, we need to create a controller to handle the logic for each of the CRUD operations. Run the following Artisan command:

php artisan make:controller PostController --api
Enter fullscreen mode Exit fullscreen mode

This creates a new controller named PostController in the app/Http/Controllers directory. The --api flag ensures that it is an API controller with only the necessary methods.

Open PostController.php and implement each method:

1. index() – Retrieve All Posts

This method returns a list of all posts.

public function index()
{
    $posts = Post::all();
    return response()->json($posts);
}
Enter fullscreen mode Exit fullscreen mode

2. store() – Create a New Post

This method stores a new post in the database.

public function store(Request $request)
{
    $request->validate([
        'title' => 'required|string|max:255',
        'content' => 'required|string',
    ]);

    $post = Post::create([
        'title' => $request->title,
        'content' => $request->content,
    ]);

    return response()->json($post, 201);
}
Enter fullscreen mode Exit fullscreen mode

3. show() – Retrieve a Single Post

This method retrieves a specific post by its ID.

public function show($id)
{
    $post = Post::findOrFail($id);
    return response()->json($post);
}
Enter fullscreen mode Exit fullscreen mode

4. update() – Update a Post

This method updates an existing post.

public function update(Request $request, $id)
{
    $post = Post::findOrFail($id);

    $request->validate([
        'title' => 'sometimes|string|max:255',
        'content' => 'sometimes|string',
    ]);

    $post->update($request->only('title', 'content'));

    return response()->json($post);
}
Enter fullscreen mode Exit fullscreen mode

5. destroy() – Delete a Post

This method deletes a post by its ID.

public function destroy($id)
{
    $post = Post::findOrFail($id);
    $post->delete();

    return response()->json(null, 204);
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Set Up Model and Validation

To ensure our Post model works with mass assignment, open the Post.php file in app/Models and define the fillable properties:

protected $fillable = ['title', 'content'];
Enter fullscreen mode Exit fullscreen mode

This allows the Post model to accept title and content during mass assignment in the store and update methods.

Step 6: Test Your API

To test the API, you can use a tool like Postman or cURL. Here are the routes you can test:

  • GET /api/posts – Retrieve all posts
  • GET /api/posts/{id} – Retrieve a specific post by ID
  • POST /api/posts – Create a new post (send a title and content in the request body)
  • PUT /api/posts/{id} – Update an existing post (send updated title and/or content)
  • DELETE /api/posts/{id} – Delete a post by ID

For example, to create a post using cURL:

curl -X POST http://localhost:8000/api/posts \
     -H "Content-Type: application/json" \
     -d '{"title": "My First Post", "content": "This is the content of my first post."}'
Enter fullscreen mode Exit fullscreen mode

You can start your server with the following command to test the API:

php artisan serve
Enter fullscreen mode Exit fullscreen mode

Now, your API is up and running!

Conclusion

Congratulations! You have successfully created a simple CRUD API with Laravel. This API allows you to create, read, update, and delete posts. From here, you can extend the API to handle more complex functionality, add authentication, or integrate it with frontend frameworks like React or Vue.js.

Laravel's expressive syntax and powerful tools make it a great choice for building APIs. Keep exploring its features and best practices to take your skills to the next level. Happy coding!

Top comments (0)