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条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站