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?

web.php に書くルーティングの基礎と書き方まとめ

Posted at

はじめに

Laravelでは、ルーティング(Routing) によって「URLと処理(コントローラやビュー)」を結びつけます。
その中でも routes/web.php は、主にWeb画面に関係するルーティングを記述する重要なファイルです。

この記事では、web.php に記述する基本的なルーティングの構文やルールをまとめていきます。


①基本のルーティング構文

Route::get('/', function () {
    return view('welcome');
});
  • Route::get() → HTTPのGETメソッドに対応(URLにアクセスしたとき)
  • '/' → URLのパス(例:http://localhost/)
  • function () { ... } → 実行する処理(クロージャ)
  • view('welcome') → resources/views/welcome.blade.php を返す

②HTTPメソッドごとの書き方

IMG_3734.jpeg

③名前付きルート(->name())

Route::get('/contact', [ContactController::class, 'index'])->name('contact.index');
  • name('contact.index') としてルートに名前をつけることで、ビューやコントローラー内でルートを簡単に呼び出せる
<a href="{{ route('contact.index') }}">お問い合わせ</a>

④コントローラーを指定するルート

use App\Http\Controllers\PostController;

Route::get('/posts', [PostController::class, 'index']);
Route::post('/posts', [PostController::class, 'store']);
Route::get('/posts/{id}', [PostController::class, 'show']);
  • [クラス名, メソッド名] 形式で、コントローラーを割り当てる
  • Route::resource() を使うともっと簡略化も可能(後述)

⑤ルートパラメータ({id}など)

Route::get('/users/{id}', [UserController::class, 'show']);
  • {id} の部分は、リクエストされたURLからパラメータとして取得可能
  • コントローラー内で受け取る:
public function show($id)
{
    // $id を使って処理
}

⑥リソースコントローラー(Route::resource)

よくあるCRUD処理(一覧、詳細、作成、保存、編集、更新、削除)を自動でまとめてくれる便利な方法:

Route::resource('posts', PostController::class);

これで以下のようなルートが自動生成されます:
IMG_3735.jpeg

⑦ルートグループ(共通のprefixやmiddlewareをまとめる)

Route::prefix('admin')->middleware('auth')->group(function () {
    Route::get('/dashboard', [AdminController::class, 'dashboard']);
});
  • /admin/dashboard のようなURLが作れる
  • auth ミドルウェアを共通で適用できる

⑧よくある注意点

  • web.php に書いたルートはすべて ウェブブラウザ向け(セッション・CSRF保護あり)
  • APIルートは routes/api.php に記述(stateless)

⑧まとめ

IMG_3736.jpeg

Laravelにおいてルーティングはアプリの入口
しっかりと構文とルールを理解しておくと、後のコントローラー・ビュー連携もスムーズに書けるようになります!

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?