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 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题