LoginSignup
5
4

More than 3 years have passed since last update.

Laravel ルーティング(web.php)の設定

Last updated at Posted at 2019-11-29

Laravelのルーティング設定についてまとめました。

ルーティングとは、リクエストURLに応じて処理の受け渡しを決定する仕組みです。

ルーティングの設定

routes/web.phpに処理を記述します。

まず、useの処理を追記

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

// 追記
Route::get('hello', 'HelloController@index');

デフォルトは、return view('welcome');となっています。

新たにルートを定義するには、下記のように記述します。

Route:get( path , action )

  • path: リクエストパス('hello'とするとhttp://127.0.0.1:8000/helloがURLに表示)
  • action: 実行するアクション(コントローラー名@アクション名)

変数の定義

1.データベースからデータを取得して値を返す処理を追記
2.Bladeテンプレートで参照する変数名を引数に設定

Route::get('/', function () {
    $変数名 = モデル名::all();
    return view('テンプレートファイル(blade)の最初の単語名', ['変数名' => $変数名 ]);
});

フォームから入力したデータを受け取る

Route::post('formのactionに指定したURI(パス)', function (Request $request) {
    $validator = Validator::make($request->all(),[
        'name' => 'required|max:255',
    ]);

    // データベースに登録する値の変数を宣言して、モデルのクラス定義からオブジェクトを作成
    $変数名 = new モデル名;
    $変数名->title = $request->name;
    $変数名->save();

    return redirect('/');

登録したデータを削除する

implicit binding(暗黙のバインディング)
→オブジェクトのID番号を返す処理

URIとidを同じ名前にすると、一致するインスタンスを返してくれる

Route::delete('URI/{id}', function(モデル名 $変数名){
    $変数名->delete();

    return redirect('/');
});

スクリーンショット 2019-11-30 9.50.41.png
※Laravelマニュアルより引用

5
4
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
5
4