Laravel 10 入門トップページ


目次

  1. API とプロジェクトの概要
  2. プロジェクトの作成と初期設定
  3. データベースのマイグレーション
  4. シーダによるコメントデータの登録
  5. モデルの生成
  6. リソースの生成
  7. GETメソッドを利用した個別コメント取得のAPI作成
  8. 日本語文字列の表示と日時の調整
  9. GETメソッドを利用したコメント一覧取得のAPI作成
  10. データのラップ
  11. POSTメソッドを利用したコメントの新規投稿APIの作成
  12. PUTメソッドを利用したコメント更新APIの作成
  13. DELETEメソッドを利用したコメント削除APIの作成
  14. シーダの拡張
  15. ページネーションの実装
  16. 個別コメントをコントローラで取得
  17. Postman の利用
  18. ユーザ情報を登録する
  19. Sanctum によるユーザ認証
  20. ログインとトークン
  21. コメントとユーザのリレーションシップ
  22. 新規投稿時にユーザIDを記録する
  23. コメントからユーザ名を表示するリレーションシップ
  24. ユーザからコメント一覧を取得するリレーションシップ
  25. 更新と削除の権限設定
  26. 発行済みトークンの取得
  27. トークンの有効期限
  28. レート制限
  29. 閲覧権限の緩和

Laravel で API を開発する

プロジェクトの作成と初期設定

ここではプロジェクトを新規に作成して初期設定を行います.まず,ubuntu にログインして laravel のディレクトリ(フォルダ)に移動します.この作業は各自の環境に合わせてください.ここの手順で ubuntu をインストールした場合は次のような操作をすると良いでしょう.

vagrant@ubuntu2204 ~ $ cd Documents/ ⏎
vagrant@ubuntu2204 Documents $ ls ⏎
laravel
vagrant@ubuntu2204 Documents $ cd laravel/ ⏎
vagrant@ubuntu2204 laravel $ pwd ⏎
/home/vagrant/Documents/laravel
vagrant@ubuntu2204 laravel $ ls ⏎
composer.phar
vagrant@ubuntu2204 laravel $

上の作業のとおり composer.phar ファイルがあることを確認してプロジェクトを作成します.なおプロジェクト名は CommentAPI にしていますが,任意の名前で設定してください.

vagrant@ubuntu2204 laravel $ php composer.phar create-project --prefer-dist laravel/laravel CommentAPI ⏎
Creating a "laravel/laravel" project at "./CommentAPI"
Installing laravel/laravel (v10.2.10)
  - Installing laravel/laravel (v10.2.10): Extracting archive
Created project in /home/vagrant/Documents/laravel/CommentAPI
> @php -r "file_exists('.env') || copy('.env.example', '.env');"
Loading composer repositories with package information
Updating dependencies
Lock file operations: 111 installs, 0 updates, 0 removals
  - Locking brick/math (0.11.0)
  - Locking carbonphp/carbon-doctrine-types (3.1.0)

...(中略)...

  - Locking voku/portable-ascii (2.0.1)
  - Locking webmozart/assert (1.11.0)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 111 installs, 0 updates, 0 removals
  - Installing doctrine/inflector (2.0.8): Extracting archive
  - Installing doctrine/lexer (3.0.0): Extracting archive

...(中略)...

  - Installing spatie/ignition (1.11.3): Extracting archive
  - Installing spatie/laravel-ignition (2.3.2): Extracting archive
43 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi

   INFO  Discovering packages.

  laravel/sail ......................................................... DONE
  laravel/sanctum ...................................................... DONE
  laravel/tinker ....................................................... DONE
  nesbot/carbon ........................................................ DONE
  nunomaduro/collision ................................................. DONE
  nunomaduro/termwind .................................................. DONE
  spatie/laravel-ignition .............................................. DONE

83 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
> @php artisan vendor:publish --tag=laravel-assets --ansi --force

   INFO  No publishable resources for tag [laravel-assets].

No security vulnerability advisories found.
> @php artisan key:generate --ansi

   INFO  Application key set successfully.

vagrant@ubuntu2204 laravel $

上のとおり,プロジェクト作成の過程で sanctum パッケージもインストールされています.これは後ほど API のユーザ認証で利用することになります.

Git によるバージョン管理を行うのであれば,最初のコミットをこのタイミングで行っておくと良いでしょう.今後もその都度コミットを重ねると良いでしょう.

vagrant@ubuntu2204 laravel $ ls ⏎
CommentAPI  composer.phar
vagrant@ubuntu2204 laravel $ cd CommentAPI/ ⏎
vagrant@ubuntu2204 CommentAPI $ git init ⏎
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint:
hint:   git config --global init.defaultBranch <name>
hint:
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint:
hint:   git branch -m <name>
Initialized empty Git repository in /home/vagrant/Documents/laravel/CommentAPI/.git/
vagrant@ubuntu2204 CommentAPI $ git add . ⏎
vagrant@ubuntu2204 CommentAPI $ git commit -m'initial commit' ⏎
[master (root-commit) 4514567] initial commit
 79 files changed, 11224 insertions(+)
 create mode 100644 .editorconfig
 create mode 100644 .env.example
 create mode 100644 .gitattributes
 create mode 100644 .gitignore
 create mode 100644 README.md
 create mode 100644 app/Console/Kernel.php
 create mode 100644 app/Exceptions/Handler.php
 create mode 100644 app/Http/Controllers/Controller.php
 create mode 100644 app/Http/Kernel.php
 create mode 100644 app/Http/Middleware/Authenticate.php
 create mode 100644 app/Http/Middleware/EncryptCookies.php
 create mode 100644 app/Http/Middleware/PreventRequestsDuringMaintenance.php
 create mode 100644 app/Http/Middleware/RedirectIfAuthenticated.php
 create mode 100644 app/Http/Middleware/TrimStrings.php
 create mode 100644 app/Http/Middleware/TrustHosts.php
 create mode 100644 app/Http/Middleware/TrustProxies.php
 create mode 100644 app/Http/Middleware/ValidateSignature.php
 create mode 100644 app/Http/Middleware/VerifyCsrfToken.php
 create mode 100644 app/Models/User.php
 create mode 100644 app/Providers/AppServiceProvider.php
 create mode 100644 app/Providers/AuthServiceProvider.php
 create mode 100644 app/Providers/BroadcastServiceProvider.php
 create mode 100644 app/Providers/EventServiceProvider.php
 create mode 100644 app/Providers/RouteServiceProvider.php
 create mode 100755 artisan
 create mode 100644 bootstrap/app.php
 create mode 100644 bootstrap/cache/.gitignore
 create mode 100644 composer.json
 create mode 100644 composer.lock
 create mode 100644 config/app.php
 create mode 100644 config/auth.php
 create mode 100644 config/broadcasting.php
 create mode 100644 config/cache.php
 create mode 100644 config/cors.php
 create mode 100644 config/database.php
 create mode 100644 config/filesystems.php
 create mode 100644 config/hashing.php
 create mode 100644 config/logging.php
 create mode 100644 config/mail.php
 create mode 100644 config/queue.php
 create mode 100644 config/sanctum.php
 create mode 100644 config/services.php
 create mode 100644 config/session.php
 create mode 100644 config/view.php
 create mode 100644 database/.gitignore
 create mode 100644 database/factories/UserFactory.php
 create mode 100644 database/migrations/2014_10_12_000000_create_users_table.php
 create mode 100644 database/migrations/2014_10_12_100000_create_password_reset_tokens_table.php
 create mode 100644 database/migrations/2019_08_19_000000_create_failed_jobs_table.php
 create mode 100644 database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php
 create mode 100644 database/seeders/DatabaseSeeder.php
 create mode 100644 package.json
 create mode 100644 phpunit.xml
 create mode 100644 public/.htaccess
 create mode 100644 public/favicon.ico
 create mode 100644 public/index.php
 create mode 100644 public/robots.txt
 create mode 100644 resources/css/app.css
 create mode 100644 resources/js/app.js
 create mode 100644 resources/js/bootstrap.js
 create mode 100644 resources/views/welcome.blade.php
 create mode 100644 routes/api.php
 create mode 100644 routes/channels.php
 create mode 100644 routes/console.php
 create mode 100644 routes/web.php
 create mode 100644 storage/app/.gitignore
 create mode 100644 storage/app/public/.gitignore
 create mode 100644 storage/framework/.gitignore
 create mode 100644 storage/framework/cache/.gitignore
 create mode 100644 storage/framework/cache/data/.gitignore
 create mode 100644 storage/framework/sessions/.gitignore
 create mode 100644 storage/framework/testing/.gitignore
 create mode 100644 storage/framework/views/.gitignore
 create mode 100644 storage/logs/.gitignore
 create mode 100644 tests/CreatesApplication.php
 create mode 100644 tests/Feature/ExampleTest.php
 create mode 100644 tests/TestCase.php
 create mode 100644 tests/Unit/ExampleTest.php
 create mode 100644 vite.config.js
vagrant@ubuntu2204 CommentAPI $

ここでは SQLite をデータベースとして利用するので,新たな空のデータベースファイルを作成しておきます.もちろんデータベースに MySQL などを利用しても構いません.その場合の設定はここを確認してください.

vagrant@ubuntu2204 CommentAPI $ pwd ⏎
/home/vagrant/Documents/laravel/CommentAPI
vagrant@ubuntu2204 CommentAPI $ ls ⏎
README.md  bootstrap      config        phpunit.xml  routes   vendor
app        composer.json  database      public       storage  vite.config.js
artisan    composer.lock  package.json  resources    tests
vagrant@ubuntu2204 CommentAPI $ cd database/ ⏎
vagrant@ubuntu2204 database $ ls ⏎
factories  migrations  seeders
vagrant@ubuntu2204 database $ touch database.sqlite ⏎
vagrant@ubuntu2204 database $ ls ⏎
database.sqlite  factories  migrations  seeders
vagrant@ubuntu2204 database $ cd .. ⏎
vagrant@ubuntu2204 CommentAPI $

データベースの設定を .env ファイルに記載します.SQLite を利用する場合は,DB_CONNECTION の項目を設定するだけで,その他 DB_HOST などの項目は削除するかコメントアウトしてください.

.env (抜粋)DB_CONNECTION=sqlite
# DB_CONNECTION=mysql
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=laravel
# DB_USERNAME=root
# DB_PASSWORD=

プロジェクトの設定は config/app.php に記載します.具体的にはタイムゾーンと言語の設定を行います.

config/app.php (抜粋)    /*
    |--------------------------------------------------------------------------
    | Application Timezone
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default timezone for your application, which
    | will be used by the PHP date and date-time functions. We have gone
    | ahead and set this to a sensible default for you out of the box.
    |
    */

    'timezone' => 'Asia/Tokyo',

    /*
    |--------------------------------------------------------------------------
    | Application Locale Configuration
    |--------------------------------------------------------------------------
    |
    | The application locale determines the default locale that will be used
    | by the translation service provider. You are free to set this value
    | to any of the locales which will be supported by the application.
    |
    */

    'locale' => 'ja',

    /*
    |--------------------------------------------------------------------------
    | Application Fallback Locale
    |--------------------------------------------------------------------------
    |
    | The fallback locale determines the locale to use when the current one
    | is not available. You may change the value to correspond to any of
    | the language folders that are provided through your application.
    |
    */

    'fallback_locale' => 'en',

    /*
    |--------------------------------------------------------------------------
    | Faker Locale
    |--------------------------------------------------------------------------
    |
    | This locale will be used by the Faker PHP library when generating fake
    | data for your database seeds. For example, this will be used to get
    | localized telephone numbers, street address information and more.
    |
    */

    'faker_locale' => 'ja_JP',

ubuntu に設定された IP アドレスを確認します.この結果,192.168.56.101 が設定されていることがわかりました.

vagrant@ubuntu2204 CommentAPI $ ip a ⏎
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 08:00:27:2d:3b:77 brd ff:ff:ff:ff:ff:ff
    altname enp0s3
    inet 10.0.2.15/24 metric 100 brd 10.0.2.255 scope global dynamic eth0
       valid_lft 77482sec preferred_lft 77482sec
    inet6 fe80::a00:27ff:fe2d:3b77/64 scope link
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 08:00:27:ed:36:c7 brd ff:ff:ff:ff:ff:ff
    altname enp0s8
    inet 192.168.56.101/24 brd 192.168.56.255 scope global eth1
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:feed:36c7/64 scope link
       valid_lft forever preferred_lft forever
vagrant@ubuntu2204 CommentAPI $

上で確認した IP アドレスとポート番号 8000 番を指定して Web サーバを起動します.

vagrant@ubuntu2204 CommentAPI $ php artisan serve --host=192.168.56.101 --port=8000 ⏎

   INFO  Server running on [http://192.168.56.101:8000].

  Press Ctrl+C to stop the server

Web ブラウザからトップページにアクセスできることを確認します.なお,API だけの開発をするのであれば,このページを利用することはありません.

laravel10-2023-api-01.png

Web サーバを停止するには Ctrl + C を押下します.

vagrant@ubuntu2204 CommentAPI $ php artisan serve --host=192.168.56.101 --port=8000

   INFO  Server running on [http://192.168.56.101:8000].

  Press Ctrl+C to stop the server

  2023-12-16 13:50:05 .................................................. ~ 1s
  2023-12-16 13:50:06 /favicon.ico ..................................... ~ 0s
^C  # Ctrl + C を押す
vagrant@ubuntu2204 CommentAPI $

なお,以降のページで API から接続する際にも Web サーバを起動しなければならないことに注意してください.

目次に戻る