はじめに
本記事をご覧いただきありがとうございます。京都の専門学校に通っているものです。今回はフロントエンドに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にテーブルを作成するためのコマンドを叩いて行きます
sail aritsan make:migration ファイル名
// 使用例 (テーブル名:news)
sail artisan make:migration create_news_table
↓のような文字が出てくれば成功です!(今回はテーブル名をtestにしています)
newsテーブルの内容を書いていく
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コマンドを叩いたときに実行される処理のこと
$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に関しては以下のサイトを参照させていただきます。
public function down(): void
{
Schema::dropIfExists('news');
}
こちらに書いてあるものは
php artisan migrate:rollback
migrateした内容を取り消したい場合に使うコマンドを叩いたときに実行される処理
デフォルトで入っている処理はテーブルを削除するという内容です。
migrateを叩く
sail artisan migrate
このような画面になれば成功です!
phpmyadminを覗いてみましょう。
しっかりtestテーブルが作成されていますね
modelの作成
modelを作成するコマンドを叩いて行きましょう
sail artisan make:model News
modelは最初を大文字にすることが多いので注意しましょう
こちらで成功です。
ではmodelの中を記述していきます
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オプションをつけることで、空の関数がデフォルトで作成されます
sail artisan make:controller ApiNewsController --resource
controllerは各単語の頭文字を大文字にして作成します
<?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にコードを書いていきます。
//allでデータの全取得
$news = News::all();
return response()->json($news);
データが大量になる場合は負荷がかかりすぎるので、ページネーションを実装した方がいいです
returnはjson形式で値を返したいので、json(データ)とします
routeの作成
laraevlでAPIのルートを定義するにはroutes/api.phpに記述していきます
Route::get('news', [ApiNewsController::class, 'index']);
Route::[リクエストタイプ]('[apiルート]', [[作成したコントローラー名]::class, '[コントローラーで作成した関数名]']);
laravelのAPIエンドポイントは http://your-project-address/api/~ になります
seederを使ったテストデータの挿入
sail artisan make:seeder NewsSeeder
こちらも頭文字を大文字にする形式です
seederでテストデータを入れるコードを書いていきます
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を実行する
public function run(): void
{
$this->call(NewsSeeder::class);
}
$this->call([作成したseeder]::class);
でseederを実行することができます。
seeder実行コマンド叩く
#seederの実行
php artisan db:seed
#クラスを選択してseederの実行
php artisan db:seed --class=PhotoTableSeeder
--class
オプションをつけることで特定のシーダーだけ実行することもできます
最後にAPIをブラウザで確認してみる
localhost/api/newsでapi.phpで指定したAPIルートから実行できている!
ここまでが、Laravelでの作業です
次回Next.js側の手順を書いていきたいと思います