2
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?

Next.jsとLaravelを使ったAPI作成と取得

Last updated at Posted at 2024-12-10

はじめに

本記事をご覧いただきありがとうございます。京都の専門学校に通っているものです。今回はフロントエンドにNext.js,バックエンドにLaravelパッケージのsail,laravel-breezeを使用したアプリケーションを作成する際にLaravel側で、APIを作成してNext側で取得しようということで始めたときに行った内容を記事にしていきたいと思います。

学生でほぼ独学での学習を進めている身なので、本記事で気になる点があればご享受いただけますと幸いです。

環境

  • m1 mac ios 15
  • docker
  • Next.js 14
  • Laravel 11
  • sail
  • laravel-breeze

環境構築

今回の環境構築に関してはこちらのサイトを参考にさせていただきました。

環境構築に関しては、ほとんど上記のサイトと同じように進めていき、適宜jsファイルをtsxにしたり、簡単なセットアップを行っただけなので、今回は省略させていただきます。

LaravelでのAPI作成

お知らせ一覧ページを作成したいということで、とりあえずお知らせテーブルを作成していきます。

MySQLにテーブルを作成するためのコマンドを叩いて行きます

Bash
sail aritsan make:migration ファイル名

// 使用例 (テーブル名:news)
sail artisan make:migration create_news_table

↓のような文字が出てくれば成功です!(今回はテーブル名をtestにしています)
migration_success.png

newsテーブルの内容を書いていく

PHP
    public function up(): void
    {
        Schema::create('news', function (Blueprint $table) {
            $table->increments('news_id');
            $table->string('news_title');
            $table->string('news_detail');
            $table->softDeletes();
            $table->timestamps();
        });
    }

upに対してテーブルの内容を書いていきます。
upとはmigrateコマンドを叩いたときに実行される処理のこと

PHP
    $table->increments('news_id');
    //オートナンバー型で、カラム名がnews_id
    //オートナンバー型や、ID型にすることで、自動的に主キーに設定される
    $table->string('news_title');
    //string型でカラム名がnews_title
    $table->string('news_detail');
    $table->softDeletes();
    //softDeleteというlaravelが提供している、論理削除機能を追加している
    $table->timestamps();
    //created_at,updated_atがテーブルに追加される

softdeleteに関しては以下のサイトを参照させていただきます。

PHP
    public function down(): void
    {
        Schema::dropIfExists('news');
    }

こちらに書いてあるものは

Bash
php artisan migrate:rollback

migrateした内容を取り消したい場合に使うコマンドを叩いたときに実行される処理
デフォルトで入っている処理はテーブルを削除するという内容です。

migrateを叩く

Bash
sail artisan migrate

migrate_success.png
このような画面になれば成功です!
phpmyadminを覗いてみましょう。

スクリーンショット 2024-12-10 23.09.38.png

しっかりtestテーブルが作成されていますね

modelの作成

modelを作成するコマンドを叩いて行きましょう

Bash
sail artisan make:model News

modelは最初を大文字にすることが多いので注意しましょう

スクリーンショット 2024-12-10 23.15.44.png

こちらで成功です。
ではmodelの中を記述していきます

PHP
class News extends Model
{
    use HasFactory;
    
    //softDeleteを使用する場合のコード
    use SoftDeletes;

    //テーブルを明示的に宣言する
    protected $table = 'news';

    //変更可能なカラムの追加
    protected $fillable = [
        'news_title',
        'news_detail',
    ];


    //デフォルト値の追加
    protected $attributes = [
        'news_category_id' => 1
    ];
}

newsテーブルにはnews_category_idというタグをつける際のテーブルをリレーションする作りになっており、とりあえず今回はデフォルト値として1をつけています

Controllerの作成

以下のコマンドを叩いてcontrollerを作成します
--resourceオプションをつけることで、空の関数がデフォルトで作成されます

Bash
sail artisan make:controller ApiNewsController --resource

controllerは各単語の頭文字を大文字にして作成します

こちらで成功です
スクリーンショット 2024-12-10 23.33.55.png

PHP
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ApiNewsController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}

データ取得だけを行いたいので、indexにコードを書いていきます。

PHP
//allでデータの全取得
$news = News::all();
return response()->json($news);

データが大量になる場合は負荷がかかりすぎるので、ページネーションを実装した方がいいです
returnはjson形式で値を返したいので、json(データ)とします

routeの作成

laraevlでAPIのルートを定義するにはroutes/api.phpに記述していきます

PHP
Route::get('news', [ApiNewsController::class, 'index']);

Route::[リクエストタイプ]('[apiルート]', [[作成したコントローラー名]::class, '[コントローラーで作成した関数名]']);

laravelのAPIエンドポイントは http://your-project-address/api/~ になります

seederを使ったテストデータの挿入

PHP
sail artisan make:seeder NewsSeeder

こちらも頭文字を大文字にする形式です

スクリーンショット 2024-12-10 23.55.30.png
こちらで成功です

seederでテストデータを入れるコードを書いていきます

PHP
use Illuminate\Database\Seeder;
use App\Models\News;
use Illuminate\Support\Str;

    News::create([
        'news_title' => Str::random(10),
        'news_detail'  => Str::random(10),
        'news_category_id'  => 1,
    ]);

今回はmodelを作成しているので、どうせならということで、modelを使ったseederの挿入をしました。
News::createでseederを作成できます。
中身については、[データを挿入したいカラム] => [データの型]::random([文字数])として、ランダムで文字列を挿入しています。
news_category_idについては、1で固定しています。

create一件で1つ分のデータが入るので、4つデータを挿入したい場合はNews::createを複製します

DatabaseSeederでNewsSeederを実行する

PHP
    public function run(): void
    {
        $this->call(NewsSeeder::class);
    }

$this->call([作成したseeder]::class);でseederを実行することができます。

seeder実行コマンド叩く

Bash
#seederの実行
php artisan db:seed
#クラスを選択してseederの実行
php artisan db:seed --class=PhotoTableSeeder

--class オプションをつけることで特定のシーダーだけ実行することもできます

最後にAPIをブラウザで確認してみる

スクリーンショット 2024-12-11 0.11.52.png

localhost/api/newsでapi.phpで指定したAPIルートから実行できている!
ここまでが、Laravelでの作業です

次回Next.js側の手順を書いていきたいと思います

2
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
2
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?