2013-05-12 66 views
1

我使用Jeffrey Ways Generator通過腳手架命令生成一些代碼。 我是OOP,Frameworks和Laravel的新手。我有一個工作方法,但只是想知道這是否是正確的做法。Laravel 4通過表格搜索模型

所以基本上我想通過輸入框搜索我的模型。

在我的index.blade.php模型中,我在頁面頂部有這段代碼。

{{ Form::open(array('url' => 'tweets/', 'method' => 'get')) }} 
    {{ Form::text('id') }} 
{{ Form::close() }} 

現在在我的微博控制器我有這個

public function index() 
    { 
     if(Input::get('id')) 
     { 
      return Redirect::action('[email protected]', array(Input::get('id'))); 
     } 

     else 
     { 

     $tweets = $this->tweet->all(); 
     // print_r($tweets); 
     return View::make('tweets.index', compact('tweets')); 
     } 
    } 

一切工作,我希望它的工作,但是這是做事的正確方法嗎?

回答

1

而不是從index()方法重定向到show()如果輸入::獲得(「ID」)設置,應直接通過更改URL提交表單到show方法。

{{ Form::open(array('url' => 'tweets/show/', 'method' => 'get')) }} 
    {{ Form::text('id') }} 
{{ Form::close() }} 

確保設立鳴叫/顯示路由/太app/routes.php

Route::get('/tweets/show', '[email protected]'); 

可能是一個更好的解決方案:

如果表單只存在顯示特定推文的鏈接(通過ID),最好設置路線和show()方法爲:

只是通過使普通鏈路(ID爲在URL)

public function show($id) 
{ 
    // Load the tweet using $id as ID instead of Input::get('id') 
} 

從那時起,你可以鏈接到它:

Route::get('/tweets/show/{id}', '[email protected]'); 

,然後在TweetsController文件改變show()功能

<a href="{{ URL::to('tweets/show/'.$tweet->id) }}">View tweet</a>