问题描述:

I am learning Laravel and have run into a problem handling missing arguments, which has also been explained here. However, the solution(s) focus primarily on named routes, but am using RESTful controllers.

TL;DR Is there some elegant solution to handle missing arguments on all of a given controller's methods without naming each one?

Route

Route::controller('accounts', 'AccountsController');

Controller

Here is a sample controller method...where the "example.com/accounts/profile/1" works, but "example.com/accounts/profile/" [with or without the trailing slash] will throw an exception. "ErrorException: Missing argument 1 for AccountsController::getProfile()"

public function getProfile($id)

{

$account = DB::table('accounts')->where('id', $id)->first();

$this->layout->content = View::make('account.profile', array('account' => $account));

}

One Attempted Solution (Doesn't work)

I've also tried this , which was a promising-looking suggestion from another question. However, it also does not work.

public function getProfile($id = NULL)

{

if ($id = NULL)

{

return Redirect::to('accounts');

} else {

$account = DB::table('accounts')->where('id', $id)->first();

$this->layout->content = View::make('account.profile', array('account' => $account));

}

}

Other Solution (Works, but is tedious)

I know that using named routes, such as the one below , to cover all of the holes will work, but this seems like such an un-elegant solution! (especially considering the suuuuper tedious process of naming all of the routes for all of the controllers that we are planning on using)

Route::get('/accounts/profile', '[email protected]');

So....

What do you all think? Is there some elegant solution to handle missing arguments on all of a given controller's methods without naming each one?

网友答案:

The default parameter option should work aside from a minor and very commonly uncaught error in php.. You're using the assignment operator in your conditional. Use

if($id == NULL)

instead of

 if($id = NULL)

or if you like

if(is_null($id) )

One of the tragedies of a dynamically typed language. Gets me more frequently than I care to admit.

相关阅读:
Top