我仍然是Laravel的新人。我正在尝试创建搜索框,以便按用户名搜索用户。
为Laravel搜索框创建控制器的最佳方法是什么?
我的观点如下:
{{ Form::search_open('/users/search') }}
{{ Form::search_box('search','admin', array('class' => 'input-medium')) }}
{{ Form::submit('Search'); }}
{{ Form::close() }}
我有如下控制器:
class Users_Controller extends Base_Controller {
public function action_search() {
$userdetail = Input::get("username");
$details = User::where('username', '=', Input::get('username')) - > first();
return Redirect::to_route("users");
}
}
答案 0 :(得分:1)
路线:
Route::get('/search', array('as' => 'user.search', 'uses' => 'user@search'));
查看:(search / index.blade.php)
{{ Form::open(URL::to_route('user.search')) }}
{{ $errors->has('username') ? $errors->first('username','<span class="error">:message</span>') : '' }}
{{ Form::text('username', Input::old('username', $username), array('class' => 'input-medium')) }}
{{ Form::submit('Search'); }}
{{ Form::close() }}
@if ( isset($user) )
@foreach ($user->results as $user)
{{ $user->first_name }}
{{ $user->last_name }}
@endforeach
@endif
控制器:(controllers / user.php)
class User_Controller extends Base_Controller
{
public function action_search()
{
$data['username'] = Input::get('username');
if(Input::get())
{
$rules=array( 'username' => 'required' );
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
{
return Redirect::back()->with_errors($validation)->with_input();
}
else {
data['user'] = User::where('username', '=', Input::get('username'));
}
}
return View::make('search.index', $data);
}
}
型号:(models / user.php)
class User extends Eloquent
{
// ...
}