Laravel学習#1 (プロジェクト作成・ルーティング設定・サーバ起動・コントローラ作成)
プロジェクト作成
laravel new <project name>
サーバ起動(止めるときは Ctrl + C)
- http://localhost:8000で起動される
php artisan serve
ルーティング設定
- ルーティングはroutes/web.appに記述する
- 第一引数にパス、第二引数にはコントローラ名@アクション名を記述する
Route::get('hello', 'App\Http\Controllers\HelloController@index'); Route::get('hello/other', 'App\Http\Controllers\HelloController@other');
コントローラ作成
php artisan make:contoller <controller name>
コントローラにはpublic function index()のようにアクションを入れる。
ルーティング設定(パラメータ入り:?だと任意)
Route::get('hello/{id?}/{pass?}', 'App\Http\Controllers\HelloController@index');
こうするとHelloControllerの中で使える
public function index($id = 'no id', $pass = 'no pass')
シングルアクションコントローラ
public function __invoke()
{
// 処理
}
__invokeを使うと、1個のクラスに1個のアクションのみとなる。他アクションは入れられない。
ルート設定は以下の通り。
Route::get('hello', 'App\Http\Controllers\HelloController');
リクエストとレスポンス
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Http\Response; class HeyController extends Controller { // public function index(Request $request, Response $response) { $html = <<<EOF <html> <body> <h1>Hey!</h1> <h3>Request</h3> <pre>{$request}</pre> <h3>Response</h3> <pre>{$response}</pre> </body> </html> EOF; $response->setContent($html); return $response; } }
引数にrequestとresponseを入れるだけで、インスタンスを使うことが出来る。
$response->url();でアクセスしたURLを返すなどのメソッドがある。