【Laravel】コントローラにパラメータを渡す
前回、コントローラーの基本形について書きました。今回はコントローラーにパラメーターを渡す方法について紹介します。
前回作成したHelloController.phpに以下の赤枠の部分を加えます。index関数で2つのパラメータ($user, $pass)を受取りHTML上で表示させます。
ソースコード全文はこちらです。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class HelloController extends Controller{ public function index($user='noname', $pass='unknown'){ return <<<EOF <!DOCTYPE html> <html lang="en"> <head> <title>Controller Test</title> </head> <body> <h1>Controller Test</h1> <p>{$user}</p> <p>{$pass}</p> </body> </html> EOF; } }
次にweb.phpで以下のように記述します。
Route::get('hello/{user?}/{pass?}/', 'App\Http\Controllers\HelloController@index');
以下のコマンドでサーバーを立ち上げます。
$ php artisan serve
http://127.0.0.1:8000/hello/taro/suzuki/ をブラウザで開いてみましょう。もちろんパラメータ部分(赤い部分)は任意の文字列でOKです。
以下のように表示されたら成功です。
スポンサーリンク