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?

Laravelのルーティング基本知識

Posted at

はじめに

この記事はルーティングについての備忘録になります

誤りや加筆が必要な場合は随時更新します

コントローラーへのルーティングについて

作成したコントローラーにルートを設定します。indexメソッドを実行したい場合は以下のようにルーティングを追加します。

web.php
use App\Http\Controllers\UserController;

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

ルーティングファイルについて

Laravelのルーティングはroutes/web.php または routes/api.phpで定義します。

web.php
use Illuminate\Support\Facades\Route;

Route::get('/welcome', function () {
    return 'Welcome to Laravel!';
});

このルートは、/welcomeにGETリクエストを送ると、「Welcome to Laravel!」というメッセージを表示します

apiのルーティングについて

apiへのルーティングはapi.phpに記述されておりましたが、Laravel11ではapi.phpが削除されているため、APIへのルーティングもweb.phpに書くことができます

しかし、構造の明確化やURLにapi/を含みたい場合などは、以下のコマンドでapi.phpを追加することができます

php artisan install:api

ルートパラメータについて

ルートパラメータを使うことで動的な値をURLに含めることができます

web.php
Route::get('/user/{id}', function ($id) {
    return "User ID: " . $id;
});

名前付きルートについて

名前付きルートを使うと、特定のルートに名前を付け、その名前でアクセスすることができます

web.php
Route::get('/about', function () {
    return 'About Us';
})->name('about');

// 名前付きルートを使ってリンクを生成する
// <a href="{{ route('about') }}">About Us</a>

グループルーティング

複数のルートに共通の設定を適用するために、グループルーティングを使います

web.php
Route::prefix('admin')->group(function () {
    Route::get('/dashboard', function () {
        return 'Admin Dashboard';
    });

    Route::get('/settings', function () {
        return 'Admin Settings';
    });
});

この設定では、/admin/dashboardや/admin/settingsのように、すべてのルートがadminプレフィックスを持ちます

ミドルウェアの使用

特定のルートに対して、リクエスト処理の前後に何らかの処理を行いたい場合に、ミドルウェアを使用します

web.php
Route::middleware(['auth'])->group(function () {
    Route::get('/profile', function () {
        return 'User Profile';
    });
});

ここでは、authというミドルウェアが適用され、認証されたユーザーのみが/profileへアクセスできるようになります

認証されていないユーザーはauthによって設定されたルートにリダイレクトされます

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?