In the Laravel controller, I have several methods that all start with fetching a database record, after checking whether the data has been found or the rendering continues, or if there is no data, go to page 404.
Here is an example:
function get_show_user($id) { $user = static::get_user($user_id); if (!$user) { return Response::error('404', static::$some_common_error404_message); } return View::make('users.show_readonly_user_data')->with('user', $user); } function get_edit_user($id) { $user = static::get_user($user_id); if (!$user) { return Response::error('404', static::$some_common_error404_message); } return View::make('users.display_edit_user_form')->with('user', $user); }
So, I repeat the entire if (!$user) in these methods, even if they all do the same.
I would like to do something like this:
function get_show_user($id) { $user = Users::find($id); static::go404_if_null($user); return View::make('users.show_readonly_user_data')->with('user', $user); } function get_edit_user($id) { $user = Users::find($id); static::go404_if_null($user); return View::make('users.display_edit_user_form')->with('user', $user); }
What would be the best way to implement such a DRY feature?
Obviously, the simple method return Response::error('404') will not work in the general existence check method, since it will only return from this method.
It seems that Event::fire('404') not perfect either because it does not end the method in which it was run.
You may need to use an exception, but I'm not sure about this or how to do it in Laravel. Where should I catch the 404 controller exception?
source share