Laravel5.1入門その2
app/Http/routes.phpを触る。
text/plain
<?php Route::get('/', function () { return view('welcome'); }); // 文字列を返す Route::get('/ping', function () { return 'pong'; });
pong
ただ、このままだと、Content-typeが
Content-Type: text/html; charset=UTF-8
なので、
<?php Route::get('/ping', function () { return response('pong')->header('Content-Type', 'text/plain'); });
とすると、
Content-Type: text/plain; charset=UTF-8
になる。
response()はIlluminate\Http\Responseインスタンスを作るヘルパらしい。
application/json
もっと簡単で、arrayを返却すればContent-typeごとJSON形式にしてくれる。
<?php Route::get('/myjson', function () { return ['foo' => 'bar', 'hoge' => [1,2,3]]; });
Content-Type: application/json {"foo":"bar","hoge":[1,2,3]}
コントローラ
コントローラを作って動かしてみる。
$ php artisan make:controller PhotoController
app/Http/Controllers/PhotoController.php
<?php public function index() { return view('photos.index'); // resouces/viewsからの相対 }
app/Http/routes.php
Route::get('/photos', 'PhotoController@index');
ビューのディレクトリを作る。
$ mkdir resources/views/photos
resources/views/photos/index.blade.php
bladeエンジンを使うには.blade.phpにしなければならない。(下のは素のHTMLだけど)
<html><h1>Photo</h1></html>
http://localhost/photos にアクセス。