【问题标题】:Passing ID from Laravel show to Datatables route将 ID 从 Laravel show 传递到 Datatables 路由
【发布时间】:2019-11-13 15:41:40
【问题描述】:

我相信我已经很接近了,但正在努力解决如何将给定 ID 从我的 show 方法传递到关联的 showdata 中,以便数据表可以仅显示该 ID 的关联数据。

当我硬编码一个 ID 或完全删除 where 语句时,该代码有效。我的目标是让数据表清单与给定集合相关联的项目。

路线:

Route::resource('collections', 'CollectionsController');
Route::get('collectionsdata/{id}', 'CollectionsController@showdata');

Show.blade.php:

var id = {{ $collection->id }}
        $(function () {...

$('#item-table').DataTable({
                //processing: true,
                serverSide: true,
                ajax: "/collectionsdata/"+ id,
                columns: [
                    //{data: 'id', name: 'id'},
                    {data: 'id', name: 'id'},
                    {data: 'collection_id', name: 'collection_id'},
                    {data: 'type_id', name: 'type_id'},
                    {data: 'collection.title', name: 'collection.title'},
                    {data: 'type.name', name: 'type.name'},
                    {data: 'updated_at', name: 'updated_at'},
                ]
            });

集合控制器:

    public function show(Collection $collection)
    {
        $collection->load('items.type')->get();

        //dd($collection);
        return view ('collections.show', compact('collection'));
    }

    public function showdata()
    {
        $data = Item::with('collection', 'type')->where('collection_id', $id);

        return Datatables::of($data)->make(true);
    }

SHOW 本身运行良好,var id 在刀片中运行良好 - 我想我只是在控制器中遗漏了一些东西来获取 id 并最终在 $data 上创建所需的查询以返回数据表。

【问题讨论】:

    标签: php ajax laravel datatables


    【解决方案1】:

    您只需在 showdata 中有一个参数,即您从 URL 传递的 id 参数

    public function showdata($id)
    {
        $data = Item::with('collection', 'type')->where('collection_id', $id);
        return Datatables::of($data)->make(true);
    }
    

    【讨论】:

      【解决方案2】:

      是的。您在 show 方法中缺少 Request $request 以从路由中检索 $id。

      use Illuminate\Http\Request;
      
      public function showdata(Request $request)
      {
          $collection_id = $request->id;
      
          $data = Item::with('collection', 'type')->where('collection_id', $id);
      
          return Datatables::of($data)->make(true);
      }
      

      您也可以直接从控制器中检索 id,而不是使用 $request

      public function showdata($id)
      {
          $data = Item::with('collection', 'type')->where('collection_id', $id);
      
          return Datatables::of($data)->make(true);
      }
      

      【讨论】:

      • 你可以在我的悲伤洞穴中找到我...谢谢!!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      • 2021-02-25
      • 1970-01-01
      • 2018-05-31
      • 2014-01-06
      • 1970-01-01
      • 2021-01-28
      相关资源
      最近更新 更多