laravel 10 rest api crud operation example

In this section we will see rest api crud operation app using laravel 10. For this tutorial we will create simple but clean laravel 10 api crud using Request for validation, Resource for showing important & clean data.


Step 1: Install Laravel & Connect Database

Installing a fresh new laravel 10 application, so head over to the terminal, type the command, and create a new laravel app.

composer create-project laravel/laravel apicrud


Now, you have to connect the laravel app to the database, hence open the .env configuration file and add the database credentials as suggested below.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password


Step 2: Create Model Request and Resource, Api Controller & route

Create Post Modal with migration

php artisan make:model Post -m

Create Post Request for validation

php artisan make:request StorePostRequest

Create Post Resource for show clean data

php artisan make:resource PostResource

Create Post Api controller

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


create_posts_table.php

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};


app/Http/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'];
}


app/Http/Requests/StorePostRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StorePostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array|string>
     */
    public function rules(): array
    {
        return [
            'title' => ['required', 'max:70'],
            'content'  => ['required']
        ];
    }
}


app/Http/Resources/PostResource.php 

<?php

namespace App\Http\Resources;

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

class PostResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'content' => $this->content,
            'created_at' => $this->created_at,
        ];
    }
}


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
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $posts = Post::all();
        return PostResource::collection($posts);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StorePostRequest $request)
    {
        $posts = Post::create($request->all());
        
        return new PostResource($posts);
    }

    /**
     * Display the specified resource.
     */
    public function show(Post $post)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Post $post)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(StorePostRequest $request, Post $post)
    {
        $post->update($request->all());
        
        return new PostResource($post);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Post $post)
    {
        $post->delete();

        return response(null, 204);
    }
}


routes/api.php

<?php

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

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
Route::apiResource('posts',PostController::class)->except([
    'create', 'show', 'edit'
]);


Run laravel 10 app

php artisan serve


Step 3: Test Laravel 10 API CRUD App in Postman

Store Post data

http://localhost:8000/api/posts

laravel 10 rest api crud operation store

laravel 10 rest api crud operation store

Update Post data

http://localhost:8000/api/posts/1

laravel 10 rest api crud operation update

laravel 10 rest api crud operation update

Showing All Post data by GET

http://localhost:8000/api/posts

{
    "data": [
        {
            "id"1,
            "title""Laravel 10 REST API CRUD Operation Update",
            "content""Lorem ispm Update",
            "created_at""2023-07-04T16:11:41.000000Z"
        },
        {
            "id"2,
            "title""Laravel 10 api Example 2",
            "content""lorem ispm",
            "created_at""2023-07-04T16:11:41.000000Z"
        },
        {
            "id"3,
            "title""Laravel 10 REST API CRUD Operation Example",
            "content""Lorem ispm",
            "created_at""2023-07-04T16:13:32.000000Z"
        }
    ]
}


Delete Post data

http://localhost:8000/api/posts/1

laravel 10 rest api crud operation delete

laravel 10 rest api crud operation delete