Lädt...

🔧 How to Build a CRUD API with Laravel for Beginners


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

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

Once installed, navigate to the newly created project folder:

cd crud-api

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

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

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();
    });
}

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

php artisan migrate

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);

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

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);
}

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);
}

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);
}

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);
}

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);
}

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'];

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."}'

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

php artisan serve

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!

...

🔧 How to Build a CRUD API with Laravel for Beginners


📈 40.03 Punkte
🔧 Programmierung

🔧 FastAPI Beyond CRUD Part 3 - Buiding a CRUD REST API


📈 31.16 Punkte
🔧 Programmierung

🔧 Laravel for Beginners #3 - The CRUD Operations


📈 30.92 Punkte
🔧 Programmierung

🔧 Simplifying API responses in Laravel with kolirt/laravel-api-response package


📈 27.06 Punkte
🔧 Programmierung

🔧 How to Build an API with Laravel Breeze in Laravel 11


📈 26.8 Punkte
🔧 Programmierung

🔧 Laravel 11 Vue.js 3 CRUD Application with Composition API


📈 26.77 Punkte
🔧 Programmierung

🔧 Building a CRUD API with Laravel and Sanctum


📈 26.77 Punkte
🔧 Programmierung

🔧 How to Create a CRUD API – NodeJS and Express Project for Beginners


📈 26.75 Punkte
🔧 Programmierung

🎥 Upgrade Laravel 11 to Laravel 12 #laravel #thecodeholic


📈 26.55 Punkte
🎥 Video | Youtube

🎥 Using Laravel Breeze Starter Kits in Laravel 12 #laravel #thecodeholic #laravel12


📈 26.55 Punkte
🎥 Video | Youtube

🎥 Print SQL Queries in Laravel #laravel #thecodeholic #laravelcourse #php #laravel


📈 26.55 Punkte
🎥 Video | Youtube

🎥 Create First Laravel Project using Laravel Herd #laravel #laravelproject #laravelphp


📈 26.55 Punkte
🎥 Video | Youtube

🔧 [Laravel v11 x Docker] Efficiently Set Up a Laravel App Dev Environment with Laravel Sail


📈 26.55 Punkte
🔧 Programmierung

🎥 Laravel 11 in 11 hours - Laravel for Beginners Full Course


📈 26.53 Punkte
🎥 Video | Youtube

🎥 Laravel 11 in 11 hours - Laravel for Beginners Full Course


📈 26.53 Punkte
🎥 Video | Youtube

🎥 I Built Laravel Course for Beginners #laravel #laravelphp #thecodeholic


📈 26.53 Punkte
🎥 Video | Youtube

🎥 One of the Best Laravel for Beginners Course #laravel #thecodeholic


📈 26.53 Punkte
🎥 Video | Youtube

🔧 Laravel 11 for Beginners: Step-by-Step Guide to Install Laravel 11


📈 26.53 Punkte
🔧 Programmierung

🔧 How to Build a Generic CRUD Controller in Laravel for Multiple Resources


📈 26.51 Punkte
🔧 Programmierung

🔧 Introducing saksh-crud: Simplify Your Node.js CRUD Operations


📈 26.48 Punkte
🔧 Programmierung

🔧 FastAPI Beyond CRUD Part 6 - CRUD With Async SQLModel (An Introduction to Dependency Injection)


📈 26.48 Punkte
🔧 Programmierung

🕵️ rConfig up to 3.9.4 lib/crud/search.crud.php Command privilege escalation


📈 26.48 Punkte
🕵️ Sicherheitslücken

🔧 Laravel API Tutorial: Build, Document, and Secure a REST API


📈 22.63 Punkte
🔧 Programmierung

🔧 Building a CRUD API with ASP.NET Core Web API and PostgreSQL


📈 22.6 Punkte
🔧 Programmierung

🔧 Building a CRUD API with ASP.NET Core Web API and PostgreSQL


📈 22.6 Punkte
🔧 Programmierung

🔧 🚀 Create a CRUD web API with DATA API builder and EFCORE Power Tools 🚀


📈 22.6 Punkte
🔧 Programmierung

🔧 Build a CRUD Rest API in Python using Flask, SQLAlchemy, Postgres, Docker


📈 22.34 Punkte
🔧 Programmierung

🔧 Build a CRUD Rest API in JavaScript using Nodejs, Express, Postgres, Docker


📈 22.34 Punkte
🔧 Programmierung

🔧 Build CRUD RESTful API Using Spring Boot 3, Spring Data JPA, Hibernate, and MySQL Database


📈 22.34 Punkte
🔧 Programmierung

🔧 🚀 Build a Simple CRUD API in PHP with the Flight Framework


📈 22.34 Punkte
🔧 Programmierung

🔧 How to Build a Serverless CRUD REST API with the Serverless Framework, Node.js, and GitHub Actions


📈 22.34 Punkte
🔧 Programmierung

matomo