2014-04-19 79 views
2

我剛開始嘗試Laravel 4.1,並且必須使用Laravel 4.0的教程,因此我必須對代碼的某些部分進行疑難解答。 有一部分我無法排除故障,我需要一些幫助。在Laravel 4.1中重定向的問題

這些都是涉及到的路線:

Route::get('authors/{id}/edit', array('as'=>'edit_author', 'uses'=>'[email protected]_edit')); 

Route::put('authors/update', array('uses'=>'[email protected]_update')); 

,這些都是在控制器的動作:

public function get_edit($id){ 
    return View::make('authors.edit')->with('title', 'Edit Author')->with('author', Author::find($id)); 
} 

public function put_update(){ 
    $id = Input::get('id'); 
    $author = array(
      'name' => Input::get('name'), 
      'bio' => Input::get('bio'), 
      ); 
    $validation = Author::validate($author); 
    if ($validation->fails()){ 
     return Redirect::route('edit_author', $id); 
    }else{ 
     Author::update($id, $author); 
     return Redirect::route('view_author', $id); 
    } 
} 

注意的是,在路線我使用(編號),而不是(:任何),因爲後者不適合我。

在我的瀏覽器中,get_edit函數首先運行正常,但是當我點擊提交按鈕並且它應該執行put_update時,是否應該將我重定向到view_author或返回到edit_author,它只是給我一個NoFoundHttpException 。

正如更多的信息,我使用默認.htacces這是這一個:

<IfModule mod_rewrite.c> 
    <IfModule mod_negotiation.c> 
     Options -MultiViews 
    </IfModule> 

    RewriteEngine On 

    # Redirect Trailing Slashes... 
    RewriteRule ^(.*)/$ /$1 [L,R=301] 

    # Handle Front Controller... 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteRule^index.php [L] 
</IfModule> 

回答

1

由於您使用4.1所以它應該是{id}(:any),並確保您使用的是正確的方式來產生形式如下:

Form::open(array('action' => array('[email protected]_update', $author->id), 'method' => 'put')) 

同樣關閉表格使用Form::close()。由於您沒有使用RESTful控制器,因此您可以使用方法名稱作爲update而不是put_update,並且對於RESTful方法使用putUpdate而不是put_update。所以,你可以使用類似的路線:

Route::put('authors/update', array('uses'=>'[email protected]')); 

然後,該方法應該是:

public function update($id) 
{ 
    // ... 
    if ($validation->fails()){ 
     return Redirect::back()->withInput()->withErrors($validation); 
    } 
    else{ 
     Author::update($id, $author); 
     return Redirect::route('view_author', $id); 
    } 
} 

所以形式應該是這樣的:

Form::open(array('action' => array('[email protected]', $author->id), 'method' => 'put')) 

也能改變你的編輯route本:

Route::get('authors/edit/{id}', array('as'=>'edit_author', 'uses'=>'[email protected]')); 

在該方法中進行更改:

public function edit($id) 
{ 
    //... 
} 
+0

謝謝,這非常有幫助。 原來我是這樣打開我的表格: <?php echo Form :: open(array('url'=>'authors/update','_ method'=>'PUT')); ?> ...因爲這就是我在我的「創建」形式,並且工作正常。現在我也改變了我的創建表格開放線... 另外,我使用一個寧靜的控制器...或者我想,因爲我在我的控制器「public $ restful = true;」做了這個...「 但是,這又是我第一天使用laravel,所以如果你知道4.1的教程,我會很感激,因爲使用4.0 tut並不容易。 無論如何,非常感謝您的幫助! – arrigonfr

+0

很高興有幫助,歡迎您:-) –