Laravel - 25. エラー処理
ここからはLaravelのエラー処理について学習します。LaravelにはWebアプリケーションで発生するエラー(例外)を効率よく管理する仕組みが用意されています。Laravelのエラー処理の詳細に入る前に、まずモデルの細かな挙動について学習していくことにします。
ここではあらたに HelloController に show アクションを追加して Message モデルの挙動について確認します。ルーティングの定義をしている routes/web.php ファイルから編集していきましょう。
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get("/hello", "HelloController@index");
Route::get("/hello/create", "HelloController@create");
Route::post("/hello/store", "HelloController@store");
Route::get("/hello/show/{id}", "HelloController@show");
ルーティングファイルに Route::get("/hello/show/{id}", "HelloController@show"); を追記しています。
ここで "/hello/show/{id} のように、パスにパラメータ( id )を定義できます。この id パラメータには、コントローラのアクションメソッドの引数によってアクセス可能です。たとえば /hello/show/1 のようなパスにアクセスされた場合は、後述する show メソッドの引数 $id に "1" が代入されます。
続いて app/Http/Controllers/HelloController.php を編集して show アクションを追加します。
<?php
namespace App\Http\Controllers;
use App\Message;
use App\Http\Requests\MessageRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class HelloController extends Controller
{
public function index(Request $request)
{
$count = $request->session()->get("count", 0);
$count++;
$request->session()->put("count", $count);
$title = "Hello Model!";
$messages = Message::orderBy("id")->get();
return view("hello/index", compact("title", "messages"));
}
public function create()
{
return view("hello/create");
}
public function store(MessageRequest $request)
{
$text = $request->input("text");
$message = new Message();
$message->text = $text;
$message->save();
$request->session()->flash("message", "Added message.");
return redirect("/hello");
}
public function show($id)
{
$message = Message::findOrFail($id);
return view("hello/show", compact("message"));
}
}
show アクションは $id 引数でルーティング時に定義したパスパラメータを取得しています。次に $id 引数を使って Message クラスの find メソッドではなく findOrFail メソッドを呼び出しています。 Message::findOrFail メソッドはデータを取得できなかった場合に ModelNotFoundException をスローします。またLaravelはアクションメソッドから ModelNotFoundException がスローされた場合はデフォルトで404ページを表示します。
最後に show アクションから呼び出されるビューファイル( resources/views/hello/show.blade.php )を作成しておきましょう。
@extends('layout.app')
@section('content')
<h1>{{ $message->text }}</h1>
@endsection
ここではレイアウトファイルに 'layout.app' を指定して $message 変数の text プロパティを出力しています。
動作確認
それでは HelloController に show アクション を追加したので、PHPのビルトインWebサーバを使ってWebアプリケーションを起動してみましょう。次のようにコマンドを入力します。
$ php artisan serve --host 0.0.0.0
Laravel development server started: http://0.0.0.0:8000
続いてブラウザを起動してWebアプリケーションにアクセスしてみましょう。
http://localhost:8000/hello/show/1

実行結果のようにデータベースに存在する id を指定した場合はメッセージが表示されます。
次にアドレスバーから以下のURLにアクセスしてみましょう。
http://localhost:8000/hello/show/100

実行結果のようにデータベースに存在しない id を指定した場合はデフォルトの404 Not Foundページが表示されます。
まとめ
- Laravelにはエラー処理の仕組みが用意されており、例外発生時の処理をカスタマイズできるようになっている
- Modelの
findOrFailメソッドはデータが見つからない場合にModelNotFoundExceptionをスローする - Laravelはアクションメソッドから
ModelNotFoundExceptionがスローされると404ページを表示する