dongluobei9359 2017-10-12 08:47
浏览 216
已采纳

如何在Laravel表单中提交表单后保留所选选项的值

I want to make when user search by country on the page refresh eg. result page to keep selected country on the option on the form.

This is what I have where I populate the dropdown

@foreach ($countries as $country)
        <option value="{!! $country->id !!}">{!! $country->name !!}</option>
@endforeach

And this is what I have tried but seems that is not correct since the value isn't selected

@foreach ($countries as $country)
    <option value="{!! $country->id !!}"  @if( old('country->id')  == $country->id) selected="selected" @endif>{!! $country->name !!}</option>
@endforeach

What's the trick here?

Here is the controller

public function search(Request $request)
{

    $searchText = strip_tags($request['q']);
    $seachLocation = strip_tags($request['l']);


    $columns =['alias','description','address1','address2','address3'];

    $query = Item::select('*');

    $query->where( 'title', 'like', '%'.$searchText.'%');

    foreach( $columns as $column) {
        $query->orWhere( $column, 'like', '%'.$searchText.'%', '%'.$seachLocation.'%');
    }

    $query->orWhereHas('category',function( $query ) use (  $searchText ) {
        $query->where('title', 'like', '%'.$searchText.'%' );
    });

    $query->orWhereHas('country',function( $query ) use (  $searchText ) {
        $query->where('name', 'like', '%'.$searchText.'%' );
    });

    $items = $query->paginate(5);
    $searchQuery = $searchText;
    $searchQueryLoc = $seachLocation;

    return view('search', compact('items','searchQuery','seachLocation'));
}
  • 写回答

3条回答 默认 最新

  • dptpn06684 2017-10-12 09:49
    关注

    I would suggest that you use session to store the selected country. For example:

    session()->put('forms.country', $request->get('country'));
    

    Then your html should become:

    <option value="{{ $country->id }}"  @if( session('forms.country')  == $country->id) selected="selected" @endif>{{ $country->name }}</option>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB代码补全插值
  • ¥15 Typegoose 中如何使用 arrayFilters 筛选并更新深度嵌套的子文档数组信息
  • ¥15 前后端分离的学习疑问?
  • ¥15 stata实证代码答疑
  • ¥50 husky+jaco2实现在gazebo与rviz中联合仿真
  • ¥15 dpabi预处理报错:Error using y_ExtractROISignal (line 251)
  • ¥15 在虚拟机中配置flume,无法将slave1节点的文件采集到master节点中
  • ¥15 husky+kinova jaco2 仿真
  • ¥15 zigbee终端设备入网失败
  • ¥15 金融监管系统怎么对7+4机构进行监管的