ルーティングとは
ルーティングとはWebサーバーに送られたHTTPリクエストを適切なコントローラーや処理に振り分ける仕組みです。例えば、http://localhost/helloにアクセスした場合、このアドレスに処理をあらかじめに割り振ることで、ブラウザがアクセスWebサーバーにアクセスしたときに適切な処理を行うことができます。
Laravelにおけるルーティングの設定方法
Laravelでは、routes/web.phpにルーティングを書き込みます。web.phpは初期で以下のようになっているはずです。
<?php
use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');
Route::middleware('auth')->group(function () {
Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});
require __DIR__.'/auth.php';
ここで、Route::getは、getメソッドでのアクセスされた時の処理を定義するものであり、以下のコードはhttp://localhostに接続したときに、welcomeというビューを表示するという設定です。
Route::get('/', function () {
return view('welcome');
});
get関数の第一引数がURI(パス)で、第二引数が処理内容となります。getのほかに、post、pache、put、deleteなどがあります。ここでは、http://localhost/hello-worldにアクセスしたときにブラウザに「Hello world from get.」と表示されるようにプログラムを追加してみます。プログラムは以下のように記述します。「require __DIR__.’/auth.php’;」の前に記述するとよいでしょう。
Route::get("/hello-world", function() {
return "Hello world from get.";
});
ブラウザで、http://localhost/hello-worldにアクセスすると、Hello world from get.と表示されたら成功です。
今回は簡単なルーティングの実装を行いました。HTTPメソッドはget以外にも、複数あるので、それらについての設定も後ほど解説します。次回はルーティングについて解説します。