LoginSignup
0
1

PHP LaravelでRESTful APIを試す

Posted at

はじめに

Larvel PHPでRESTful APIのテストをしたときの備忘録です。CRUDの内容は参考URLの通り。

Laravel8で実施しようかとやろうと思いましたが、Laravel10でも同じ書き方でできるのかなと思い、テスト的にLaravel10で実施しています。

環境

・Windows11, XAMPP PHP v8.2
・composerのインストール(EXEファイルによりインストール)

PowerShell
$ php -V
PHP 8.2.12

$ composer -V
Composer version 2.7.1

Laravel10 インストール

・Laravel10のインストール

PowerShell
$ composer create-project "laravel/laravel=10.*" --prefer-dist (フォルダ名)

・実行して確認してみる

PowerShell
$ cd (フォルダ名)
$ php artisan serve

http://127.0.0.1:8000/
にアクセスして確認する

001.png

DBの作成

・XAMPP phpmyadmin でDBを新規に作成

モデル

・make model

PowerShell
$ php artisan make:model Student -m

・app/modelsのStudent.phpを編集

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のファイルを編集

yyy_mm_dd_xxxx_create_xxx.php
<?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ファイルを編集

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=(新規作成したDBを指定)
DB_USERNAME=root
DB_PASSWORD=

・マイグレーション

PowerShell
$ php artisan migrate

・phpmyadminにてDBの中身を確認
002.png

ルーティング

・make controller

PowerShell
$ php artisan make:controller ApiController

・app/Http/controllersの ApiController.phpの編集

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にて作成済みのメソッドを参照するエンドポイントを作成

api.php
<?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']);

・ルートの確認

PowerShell
$ 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が返ってくる。

003.png

  • GET: データを取得する

GET:http://127.0.0.1:8000/api/students
GET:http://127.0.0.1:8000/api/students/2 ←IDによるデータ取得

登録されているすべてのレコードが取得できる。

004.png

  • PUT変更する PUT

PUT:http://127.0.0.1:8000/api/students/3

JSON形式でPUTを送りデータを更新する。

005.png

  • DELETE: 削除する

GET:http://127.0.0.1:8000/api/students/2

006.png

参考URL

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1