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でwebapiを使ってjsonでデータを全件受け渡す

Posted at

はじめに

laravelだったりのバックエンド側をやっていると、通常コントローラで書き書きしてビュー側にデータを渡すことが多い。

$posts = Post::get();
return view('posts.index', compact('posts'));

のような感じで。

ただ場合によってビューに返す場合以外に、jsonで返すこともある。
バックエンドで完結する場合ではなく、Reactだったりのフロントでビュー側を作成する場合だ。
この場合はとってきたデータをビューに返すのではなく、jsonで返してあげる必要がある。

今回はそんなjsonでの返し方について書いていく。

なぜフロントとバックエンドを分けるのか

  • よりモダンなWEBサイトを作成するため
  • バックエンド側とフロント側で分けて作業ができるようになるので効率的に作業を進められる

などそれ以上に分けるメリットと理由があるのだが、ものすごく理解しているわけではないので今回はこのくらいの理解で。
またいつか改めてSPAとかまとめていきたい。

WebAPIの作り方

現状やっている事的にはこれまでにLaravelでやってきたことと大きく変わることでもなさそう。
ビューに返していたデータをjsonで返せばいいだけ。
ルーティング書く場所とか若干違うためそのあたり変える。

ルーティング

Laravelを扱っていると基本的にルーティングはroute/web.phpにまとめていく。
ただWEBAPIの場合は、同じconfigにあるroute/api.phpにまとめていく。
書き方はどちらも同じような形。

api.php
<?php

use App\Http\Controllers\PostController;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

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

コントローラ

コントローラの書き方も基本的には変わらない。
返し先がビューではなくjsonとなるだけ。

postController.php
public function index()
    {
        $posts = Post::get();
        return response()->json($posts);
    }

書き方はクエリビルダ通りにかけるので、
SELECT句やWHERE句なども使って書くことができます。

上記のような形でデータを送ってあげると
json形式で送られます。

[
  {
    "id": 1,
    "name": "hoge",
    "item": "apple"
  },
  {
    "id": 2,
    "name": "hogehoge",
    "item": "banana"
  }
]

以上

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?