How to check for the existence of a DRY & Laravel-style object that many controller methods work with?

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?

+4
source share
1 answer

I think the best way to approach this is with a filter in front of your controller.

 public static $require_user = array( 'edit_user', 'show_user', ); public function before() { $route = Request::route(); if ( in_array( $route->controller_action, static::$require_user ) ) { $this->user = User::find( $route->parameters[0] ); if ( is_null($this->user) ) return Response::error('404'); } } 

Before the filters are called after your controller is constructed, but before the method is called. If a non-zero value is returned before the filter, the method is not called and, therefore, execution stops.

Here we get the current route that runs so that we can check which method will be called against our $ require_user array. This allows you to use methods that do not require a user ID, such as login.

Then we retrieve the user instance, getting the identifier from what would be passed to the method. You should probably add extra error handling.

Finally, we check to see if user null was returned, i.e. not found. If so, we return a 404 response, stopping the execution of the method.

Hope this helps!

+1
source

Source: https://habr.com/ru/post/1441126/


All Articles