【问题标题】:Laravel 4 search - in view, show value submitted in formLaravel 4 搜索 - 在视图中,显示表单中提交的值
【发布时间】:2014-11-17 11:05:39
【问题描述】:

下面是我构建的过滤器表单的开始。它工作正常,但我想做的是在我的视图中检索输入的值。所以,在这个例子中,我想显示“你搜索了'用户输入的关键字'”,并在关键字文本字段中显示这个。当我添加选择列表时,这将是相同的原则。

如果用户希望更改过滤器设置,或对结果进行分页,则始终会存储这些值。

我的问题是如何做到这一点。我很确定这在 laravel 中是可能的,但只知道如何在 PHP 中做到这一点

形式

<div class="row">  
    {{ Form::open(array('url'=>'events/search',    'class'=>'form-search', 'role'=>'form')) }}
        <div class="col-lg-6">
                <div class="input-group">
                    {{ Form::text('search', '', array('class'=>'form-control', 'placeholder'=>'Search by keyword.'))}}
                    <span class="input-group-btn">
                    {{ Form::submit('Search', array('class'=>'btn btn-default'))}}
                    </span>
                </div>
            </div>
    {{ Form::close() }}
</div>

搜索控制器

public function postSearch() {

        $search = Input::get('search');

        $events = DB::table('events')
            ->where(function($query) use ($search)
            {
                $query->where('title', 'LIKE',  '%' . $search . '%')
                ->where('date','>=', DB::raw('CURDATE()'));
            })
        ->orderBy('date', 'DESC')
        ->get();

        $this->layout->content = View::make('events.results', 
            array(
                'events' => $events
                )
            );
    }

查看

@foreach($events as $event)
        <div class="col-md-9">You search for ''</div>
          {{-- filter form will again display here --}}
        <h2>{{ HTML::link("events/$event->id/", "$event->title") }}</h2>
@endforeach

【问题讨论】:

    标签: laravel laravel-4


    【解决方案1】:

    控制器:

    public function postSearch() {
    
        $search = Input::get('search');
    
        $events = DB::table('events')
            ->where(function($query) use ($search)
            {
                $query->where('title', 'LIKE',  '%' . $search . '%')
                ->where('date','>=', DB::raw('CURDATE()'));
            })
        ->orderBy('date', 'DESC')
        ->get();
    
        $this->layout->content = View::make('events.results', 
            array(
                'events' => $events,
                'search' => $search <-------- pass the search parameter to view
                )
            );
    }
    

    查看:

    @if(!empty($search))
    <div class="col-md-9">You search for {{$search}}</div>   
    @endif
    
    @foreach($events as $event)
        {{-- filter form will again display here --}}
        <h2>{{ HTML::link("events/$event->id/", "$event->title") }}</h2>
    @endforeach
    

    两个问题:

    • 一般搜索表单是GET 而不是POST。 (更容易添加书签,请在别处提供链接)
    • 将搜索词放在循环之外。

    【讨论】: