1

我在习惯 Laravel 4 中的整个路由和控制器时遇到了一些麻烦。

据我了解,路由应该只用于决定指向 URL 的位置,因此它不应该用于处理上传或类似的事情。

所以基本上我所拥有的是我的路由文件,它验证用户字段,然后我如何将它指向一个控制器来处理上传和类似的一切。

我目前有以下代码,但是当验证通过并且应该转到控制器文件时,它只显示一个空白屏幕。

任何帮助将不胜感激。

Route::post('create-profile', function()
{

// Validation rules
$rules = array(
    'username' => 'required|unique:users,username|min:4|alpha_dash',
    'emailaddress' => 'required|email|unique:users,email',
    'country' => 'required',
    'state' => 'required',
    'genre' => 'required',
    'filename' => 'image',
    'password' => 'required|min:5|confirmed',
    'password_confirmation' => 'required'
);

// Validate the inputs
$v = Validator::make( Input::all(), $rules );

// Was the validation successful?
if ( $v->fails() )
{

    // Something went wrong
    return Redirect::to('create-profile')->withErrors( $v )->withInput(Input::except('password', 'password_confirmation'));

} else {

            // Here is where it seems to all go wrong.
    Route::get('create-profile', 'CreateProfileController@processSignup');

}

});
4

1 回答 1

5

假设您的网址将是:

http://site.com/create-profile

我所展示的并不理想,但我认为您的代码应该更像下面的代码:

路由.php

<?php

Route::post('create-profile', 'CreateProfileController@processSignup');
Route::get('create-profile', 'CreateProfileController@signup');

CreateProfileController.php

<?php

Class CreateProfileController extends Controller {

    public function processSignup()
    {

        // Validation rules
        $rules = array(
            'username' => 'required|unique:users,username|min:4|alpha_dash',
            'emailaddress' => 'required|email|unique:users,email',
            'country' => 'required',
            'state' => 'required',
            'genre' => 'required',
            'filename' => 'image',
            'password' => 'required|min:5|confirmed',
            'password_confirmation' => 'required'
        );

        // Validate the inputs
        $v = Validator::make( Input::all(), $rules );

        // Was the validation successful?
        if ( $v->fails() )
        {
            // Something went wrong
            return Redirect::to('create-profile')->withErrors( $v )->withInput(Input::except('password', 'password_confirmation'));
        }

        return View::make('success');
    }

    public function signup()
    {
        return View::make('signup');    
    }   
}

It's better to have all your routes pointing to controllers actions and let them do the job and, also, it's a little more readable and easy to understand.

Using resource controllers, you can reduce your routes names:

Route::resource('profile', 'ProfileController', array('only' => array('create', 'store')));

Wich will give you those routes:

http://site.com/profile/create
http://site.com/profile/store
于 2013-06-11T06:00:41.250 回答