0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravelで Vue.js, Inertia.js を使用してREST APIからデータを取得する方法

Last updated at Posted at 2024-01-22

Laravelで Vue.js, Inertia.js を使用してREST APIからデータを取得する方法

Laravelをバックエンドとして、Vue.js with Inertia.jsをフロントエンドに使用し、REST APIから情報を取得する方法を紹介する。

  • 前提条件
    ・laravelのプロジェクトが作られている
    ・Vue.js, Inertia.jsがインストールされている
    ・APIキーをすでに持っている
    ・Guzzleがインストールされている

手順 1: envファイルの設定

まず、Laravelプロジェクトの.envファイルにAPIキーとAPIエンドポイントのベースURLを追加する。

.env
API_KEY=あなたのAPIキー
API_BASE_URL=あなたのAPIエンドポイントのベースURL

手順 2: コントローラの作成

LaravelでAPIデータを取得するためのコントローラを作成する。

php artisan make:controller ApiController

手順 3: コントローラの編集

作成したApiControllerにGuzzleを使用してAPIからデータを取得する処理を追加する。

namespace App\Http\Controllers;

use GuzzleHttp\Client;
use Illuminate\Http\Request;

class ApiController extends Controller
{
    public function fetchData()
    {
        $client = new Client();
        $response = $client->request('GET', env('API_BASE_URL'), [
            'headers' => [
                'Authorization' => 'Bearer ' . env('API_KEY'),
            ],
            'verify' => false  // SSL認証を無視する設定(開発環境でのみ使用)
        ]);

        $data = json_decode($response->getBody(), true);
        return $data;
    }
}

手順 4: ルートの定義

APIデータ取得用のルートをroutes/web.phpに定義する。

use App\Http\Controllers\ApiController;

Route::get('/api/data', [ApiController::class, 'fetchData']);

手順 5: Vueコンポーネントの作成

Vue.js with Inertia.jsでAPIデータを表示するコンポーネントを作成する。

// resources/js/Pages/ApiData.vue

<template>
  <div>
    <h1>API Data</h1>
    <div v-if="data">
      {{ data }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: null
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      axios.get('/api/data')
        .then(response => {
          this.data = response.data;
        })
        .catch(error => {
          console.error(error);
        });
    }
  }
};
</script>

手順 6: Vueコンポーネントのルート定義

Inertia.jsを使用してVueコンポーネントをレンダリングするためのルートを定義する。

// routes/web.php

use Inertia\Inertia;

Route::get('/api-view', function () {
    return Inertia::render('ApiData');
});

手順 7: テスト

ブラウザで[http://your-laravel-app.test/api-view]にアクセスし、APIから取得したデータが表示されることを確認する。

※最初のルートはAPIデータの取得用であり、二番目のルートはそのデータを表示するフロントエンドページを提供するためのもの。フロントエンドとバックエンドの処理が分離されており、それぞれが独立した役割を持っている。

注意点

  • 自己署名のサイトでセキュリティエラーを避けるためには、Guzzleのリクエスト時にverifyオプションをfalseに設定することができます。ただし、これはセキュリティリスクを伴うため、開発環境でのみ使用してください。
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?