首页
Preview

使用 Laravel 11 实现一个简单的 RESTful API

前言

虽然一般情况下我们通常需要进行验证和异常处理,但是这次主要是介绍API的实施步骤,所以其他的简单介绍一下就过了。

创建Laravel项目

使用 Composer 命令安装 Laravel 10。

composer create-project --prefer-dist laravel/laravel projectName

其中,projectName是你的项目名称

设置API

php artisan install:api

快速创建模型(Model)、工厂(Factory)、迁移(Migration)和种子(Seeder)

php artisan make:model Todo -mfs
# INFO Model [app/Models/Todo.php] created successfully.
# INFO Factory [database/factories/TodoFactory.php] created successfully.
# INFO Migration [database/migrations/create_todos_table.php] created successfully.
# INFO Seeder [database/seeders/TodoSeeder.php] created successfully.

创建 Model 数据模型和其对应的数据表(table)

    php artisan make:model Todos -m

内容如下:

//create_todos_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('todos', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->timestamps();
        });
    }

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

接着运行migrations来创建表:

php artisan migrate

创建 Controller

php artisan make:controller TodoController --resource

Laravel 带有资源控制器的概念,资源控制器将经典的CRUD操作划分成一套具有恒定URI和调用方法的动作。

实现POST请求

  • TodoController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use app\Models\Todo;

class TodoController extends Controller
{
    public function store(Request $request) {
        $todo = Todo::create($request->only('title'));
        return response()->json(['todo' => $todo]);
    }
}
  • Models\Todo.php
<?php

namespace App\Models;

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

class Todo extends Model
{
    use HasFactory;

    protected $fillable = ['title'];
}
  • 设置 Route

routes/api.php中定义API路由:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::apiResource('todos', \App\Http\Controllers\TodoController::class);

测试

请求http://localhost:8080/api/todos接口

image.png

实现GET请求

  • TodoController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use app\Models\Todo;

class TodoController extends Controller
{
  public function index() {
      $todos = Todo::all();
      return response()->json(['todos' => $todos]);
  }
}

image.png

实现PUT请求

  • TodoController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use app\Models\Todo;

class TodoController extends Controller
{
    public function update(Request $request, $id) {
        $todo = Todo::findOrFail($id);
        $todo->update($request->only('title'));
        return response()->json(['todo' => $todo]);
    }
}

实现Delete请求

  • TodoController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use app\Models\Todo;

class TodoController extends Controller
{
    public function update(Request $request, $id) {
        $todo = Todo::findOrFail($id);
        $todo->delete();
        return response()->json(null, 204);
    }
}
Delete:http://localhost:8080/api/todos/1

版权声明:本文内容由TeHub注册用户自发贡献,版权归原作者所有,TeHub社区不拥有其著作权,亦不承担相应法律责任。 如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

点赞(0)
收藏(0)
@夜猫子
分享php文章,对你有帮助就点个关注!

评论(0)

添加评论