はじめに
Larvel PHPでRESTful APIのテストをしたときの備忘録です。CRUDの内容は参考URLの通り。
Laravel8で実施しようかとやろうと思いましたが、Laravel10でも同じ書き方でできるのかなと思い、テスト的にLaravel10で実施しています。
環境
・Windows11, XAMPP PHP v8.2
・composerのインストール(EXEファイルによりインストール)
$ php -V
PHP 8.2.12
$ composer -V
Composer version 2.7.1
Laravel10 インストール
・Laravel10のインストール
$ composer create-project "laravel/laravel=10.*" --prefer-dist (フォルダ名)
・実行して確認してみる
$ cd (フォルダ名)
$ php artisan serve
・http://127.0.0.1:8000/
にアクセスして確認する
DBの作成
・XAMPP phpmyadmin でDBを新規に作成
モデル
・make model
$ php artisan make:model Student -m
・app/modelsのStudent.phpを編集
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
use HasFactory;
protected $table = 'students';
protected $fillable = ['name', 'course'];
}
マイグレーション
・database/migrationsのファイルを編集
<?php
public function up(): void
{
Schema::create('students', function (Blueprint $table) {
// $table->id();
// $table->timestamps();
$table->increments('id');
$table->string('name');
$table->string('course');
$table->timestamps();
});
}
.envファイルを編集
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=(新規作成したDBを指定)
DB_USERNAME=root
DB_PASSWORD=
・マイグレーション
$ php artisan migrate
ルーティング
・make controller
$ php artisan make:controller ApiController
・app/Http/controllersの ApiController.phpの編集
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
#追加
use App\Models\Student;
class ApiController extends Controller
{
// logic to get all students goes here
public function getAllStudents() {
$students = Student::get()->toJson(JSON_PRETTY_PRINT);
return response($students, 200);
}
// logic to create a student record goes here
public function createStudent(Request $request) {
$student = new Student;
$student->name = $request->name;
$student->course = $request->course;
$student->save();
return response()->json([
"message" => "student record created"
], 201);
}
// logic to get a student record goes here
public function getStudent($id) {
if (Student::where('id', $id)->exists()) {
$student = Student::where('id', $id)->get()->toJson(JSON_PRETTY_PRINT);
return response($student, 200);
} else {
return response()->json([
"message" => "Student not found"
], 404);
}
}
// logic to update a student record goes here
public function updateStudent(Request $request, $id) {
if (Student::where('id', $id)->exists()) {
$student = Student::find($id);
$student->name = is_null($request->name) ? $student->name : $request->name;
$student->course = is_null($request->course) ? $student->course : $request->course;
$student->save();
return response()->json([
"message" => "records updated successfully"
], 200);
} else {
return response()->json([
"message" => "Student not found"
], 404);
}
}
// logic to delete a student record goes here
public function deleteStudent ($id) {
if(Student::where('id', $id)->exists()) {
$student = Student::find($id);
$student->delete();
return response()->json([
"message" => "records deleted"
], 202);
} else {
return response()->json([
"message" => "Student not found"
], 404);
}
}
}
・routes/api.phpの編集
ApiControllerにて作成済みのメソッドを参照するエンドポイントを作成
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
#追加
use App\Http\Controllers\ApiController;
Route::get('/students', [ApiController::class, 'getAllStudents']);
Route::post('/students', [ApiController::class, 'createStudent']);
Route::get('/students/{id}', [ApiController::class, 'getStudent']);
Route::put('/students/{id}', [ApiController::class, 'updateStudent']);
Route::delete('/students/{id}',[ApiController::class, 'deleteStudent']);
・ルートの確認
$ php artisan route:list
GET|HEAD api/students ....................... ApiController@getAllStudents
POST api/students ....................... ApiController@createStudent
GET|HEAD api/students/{id} .................. ApiController@getStudent
PUT api/students/{id} .................. ApiController@updateStudent
DELETE api/students/{id} .................. ApiController@deleteStudent
テストの実施
POSTMANにてテストを行う
- POST: データを登録する
Post:http://127.0.0.1:8000/api/students
BodyとNameをいれてSendし、record createdが返ってくる。
- GET: データを取得する
GET:http://127.0.0.1:8000/api/students
GET:http://127.0.0.1:8000/api/students/2 ←IDによるデータ取得
登録されているすべてのレコードが取得できる。
- PUT変更する PUT
PUT:http://127.0.0.1:8000/api/students/3
JSON形式でPUTを送りデータを更新する。
- DELETE: 削除する
GET:http://127.0.0.1:8000/api/students/2
参考URL