0
1

Laravelは、フロントエンドとシームレスに連携するための機能を豊富に備えています。今回は、Vue.jsやReactを使用してシングルページアプリケーション(SPA)を構築する方法を記述してみます。

目次

  1. Laravelプロジェクトのセットアップ
  2. Vue.jsの統合
  3. Reactの統合
  4. APIの作成とフロントエンドからのデータ取得

1. Laravelプロジェクトのセットアップ

まず、Laravelプロジェクトを新規に作成します。

composer create-project --prefer-dist laravel/laravel laravel-frontend-integration

プロジェクトが作成されたら、開発サーバーを起動します。

cd laravel-frontend-integration
php artisan serve

2. Vue.jsの統合

LaravelはデフォルトでVue.jsをサポートしています。まず、Node.jsとnpmをインストールし、必要なパッケージをインストールします。

npm install

次に、Vue.jsのコンポーネントを作成します。

resources/js/components/ExampleComponent.vue

<template>
    <div>
        <h1>{{ message }}</h1>
    </div>
</template>

<script>
export default {
    data() {
        return {
            message: 'Hello from Vue.js!'
        };
    }
};
</script>

このコンポーネントをアプリケーションに登録します。

resources/js/app.js

import Vue from 'vue';
import ExampleComponent from './components/ExampleComponent.vue';

const app = new Vue({
    el: '#app',
    components: { ExampleComponent }
});

次に、BladeテンプレートでVue.jsコンポーネントを使用します。

resources/views/welcome.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Vue Integration</title>
</head>
<body>
    <div id="app">
        <example-component></example-component>
    </div>
    <script src="{{ mix('js/app.js') }}"></script>
</body>
</html>

最後に、アセットをビルドします。

npm run dev

3. Reactの統合

LaravelにReactを統合する場合、次のコマンドを実行して必要なパッケージをインストールします。

composer require laravel/ui
php artisan ui react
npm install
npm run dev

Reactコンポーネントを作成します。

resources/js/components/ExampleComponent.js

import React from 'react';

class ExampleComponent extends React.Component {
    render() {
        return <h1>Hello from React!</h1>;
    }
}

export default ExampleComponent;

このコンポーネントをアプリケーションに登録します。

resources/js/app.js

import React from 'react';
import ReactDOM from 'react-dom';
import ExampleComponent from './components/ExampleComponent';

if (document.getElementById('app')) {
    ReactDOM.render(<ExampleComponent />, document.getElementById('app'));
}

次に、BladeテンプレートでReactコンポーネントを使用します。

resources/views/welcome.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel React Integration</title>
</head>
<body>
    <div id="app"></div>
    <script src="{{ mix('js/app.js') }}"></script>
</body>
</html>

最後に、アセットをビルドします。

npm run dev

4. APIの作成とフロントエンドからのデータ取得

APIエンドポイントを作成して、フロントエンドからデータを取得する方法を見てみましょう。

routes/api.php

use App\Http\Controllers\Api\UserController;

Route::get('/users', [UserController::class, 'index']);

app/Http/Controllers/Api/UserController.php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        return User::all();
    }
}

Vue.jsまたはReactからAPIを呼び出してデータを取得します。

resources/js/components/ExampleComponent.vue

<template>
    <div>
        <ul>
            <li v-for="user in users" :key="user.id">{{ user.name }}</li>
        </ul>
    </div>
</template>

<script>
export default {
    data() {
        return {
            users: []
        };
    },
    mounted() {
        axios.get('/api/users')
            .then(response => {
                this.users = response.data;
            });
    }
};
</script>

resources/js/components/ExampleComponent.js

import React, { useEffect, useState } from 'react';
import axios from 'axios';

function ExampleComponent() {
    const [users, setUsers] = useState([]);

    useEffect(() => {
        axios.get('/api/users')
            .then(response => {
                setUsers(response.data);
            });
    }, []);

    return (
        <ul>
            {users.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}

export default ExampleComponent;

まとめ

この記事では、LaravelとVue.js、Reactの統合方法、およびAPIを介してデータを取得する方法について記述しました。これにより、フロントエンドとバックエンドのシームレスな連携が可能となり、よりインタラクティブでダイナミックなアプリケーションを構築できます。

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