Building a RESTful API CRUD Application with Laravel 11

Building a RESTful API CRUD Application with Laravel 11

Building a RESTful API CRUD Application with Laravel 11

In this tutorial, we will demonstrate how to create a simple RESTful API CRUD (Create, Read, Update, Delete) application using Laravel 11. We'll focus on maintaining a clean structure and utilizing Laravel features like Requests for validation and Resources for presenting clean and essential data.

Step 1: Installation and Database Connection

First, let's install a fresh Laravel 11 application. Open your terminal and run the following command:

composer create-project laravel/laravel apicrud

Next, connect your Laravel application to the database. Open the .env configuration file and provide your database credentials:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

Step 2: Creating Models, Requests, Resources, Controllers, and Routes

Create a Post model with its migration:

php artisan make:model Post -m

Generate a Post Request for validation:

php artisan make:request StorePostRequest

Create a Post Resource for presenting clean data:

php artisan make:resource PostResource

Generate a Post API controller:

php artisan make:controller Api/PostController --model=Post

Migration File (create_posts_table.php)

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Post Model (app/Models/Post.php)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'content'];
}

Store Post Request (app/Http/Requests/StorePostRequest.php)

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StorePostRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'title' => ['required', 'max:70'],
            'content' => ['required']
        ];
    }
}

Post Resource (app/Http/Resources/PostResource.php)

<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'content' => $this->content,
            'created_at' => $this->created_at,
        ];
    }
}

Post Controller (app/Http/Controllers/Api/PostController.php)

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\Request;
use App\Http\Requests\StorePostRequest;
use App\Http\Resources\PostResource;

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::all();
        return PostResource::collection($posts);
    }

    public function store(StorePostRequest $request)
    {
        $post = Post::create($request->validated());
        return new PostResource($post);
    }

    public function update(StorePostRequest $request, Post $post)
    {
        $post->update($request->validated());
        return new PostResource($post);
    }

    public function destroy(Post $post)
    {
        $post->delete();
        return response(null, 204);
    }
}

API Routes (routes/api.php)

<?php

use App\Http\Controllers\Api\PostController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::apiResource('posts', PostController::class)->except([
    'create', 'show', 'edit'
]);

Running the Laravel 11 Application

To run the Laravel 11 application, execute the following command:

php artisan serve

This tutorial provided a step-by-step instructions for creating a RESTful API CRUD application using Laravel 11.


  • Date: