Laravel 5.7通过动态下拉菜单显示数据库列中的所有值

时间:2019-02-16 10:59:55

标签: laravel eloquent

在Laravel 5.7应用程序中,我有一个动态下拉菜单,该菜单从数据库列调用不同的值。该下拉列表采用表格形式,供用户过滤记录摘要页面上的记录。选择值将正确进入(获取)查询字符串,并且记录已正确检索到刀片视图中的表中。我无法解决的是如何从下拉菜单中检索所有值,例如,如果用户不想选择单个值,则在下拉菜单的开始处具有“全部”默认值。如果用户选择默认值-“ all”-这将返回所有记录,无论其优先级如何。任何指导将不胜感激。

控制器

public function summary(Request $request)
{
  $priorities = DB::table('tasks')->where('user_id', auth()->id())->distinct()->orderBy('priority', 'asc')->pluck('priority');

  $priority = $request->query('priority');
  $end = $request->query('end');
  $start = $request->query('start');
  $all = $request->query('priority' == "all"){
  DB::table('tasks')->pluck('priority')};

  $result = DB::table('tasks')
              ->whereBetween('date', array($start, $end))
              ->where('priority', '=', $priority || $all)
              ->where('user_id', auth()->id())
              ->orderBy('priority', 'asc')
              ->get();

  return view('/summary', compact('priorities', 'result'));
}

查看

<label for="distance">Priority:</label><br> 
<select class="form-control" name="priority" id="priority"> 
  <option value="all">---ALL---</option>
  @foreach ($priorities as $priority)
  <option value ="{{ $priority }}">{{ $priority }}</option>
  @endforeach
</select>

如果用户选择默认值“全部”,则该记录将返回所有记录,无论其优先级如何。

2 个答案:

答案 0 :(得分:0)

检查您从

之类的请求中获得的值
$priority = $request->query('priority');

 $result = DB::table('tasks')
 ->whereBetween('date', array($start, $end))
 ->where('user_id', auth()->id())

  if($priority=="all"){
   $result = $result->where('priority', '=',$all);
  }else{
   $result = $result->where('priority', '=', $priority );
  }

  $result = $result->orderBy('priority', 'asc')
            ->get();

答案 1 :(得分:0)

var e = document.getElementById("priority");
var all = e.options[e.selectedIndex].text;

if(all === "all") {
    var base_url = 'http://localhost/laravel/get-priority'
 $.ajax({
          type: "GET",
          url : base_url+"/all",
          data : dataString,
          success : function(data){
             $.each(data, function(key, value){
                       // alert(key);
                        $('#priority').append('<option value="'+value.id+'">' + value.priority+ '</option>');

                    });
          }
}

和您的控制器中

 $priority = $request->query('priority');

 $result = DB::table('tasks')
     ->whereBetween('date', array($start, $end))
     ->where('user_id', auth()->id());


  if($priority=="all"){
      $all = $request->query('distance' == "all"){
          DB::table('sessions')->pluck('distance');
      }
      $result = $result->where('priority', '=',$all);
  }else{
      $result = $result->where('priority', '=', $priority );
  }

  $result = $result->orderBy('priority', 'asc')
            ->get();