I have ‘post’ table in my database. In post table, I have ‘LanguageID’ column. When I store/save data, It will make two records, first record with language id = 1 and the second record with language id = 2. Now, I want to show all ‘post’ data separately.
Controller
public function index(Request $request) { $languages = Language::where('IsActive', 1)->get(); if($request->ajax()) { foreach ($languages as $lang) { $post = Post::where('LanguageID', $lang->id)->get(); } return Datatables::of($post) ->addColumn('action', function($post){ return '<a id="edit" class="btn btn-info" href="post/' . $post->id . '/edit"> <i class="glyphicon glyphicon-edit icon-white"></i> Edit </a> <button type="button" class="btn btn-danger" onclick="checkDelete('.$post->id.', this);" data-token="{{ csrf_token() }}"> <i class="glyphicon glyphicon-trash icon-white"></i> Delete </button>'; }) ->make(true); } return view('pages.back-end.lists.post')->with('languages', $languages); }
This is my yajra
$(function(){ $("#data-post").DataTable({ processing: true, serverSide: true, ajax:{ url: "{{ url("post") }}", data:{ _token: "{{csrf_token()}}", languageid: languageid} }, columns: [ { data: 'PostDate', name: 'PostDate'}, { data: 'PostTitle', name: 'PostTitle' }, { data: 'PostSlug', name: 'PostTitle' }, { data: 'action', name: 'action'} ] });
});
Answer
You have to parse the language ID with doing like this in you dataTable.php
public function language($id){ $this->language = $id; return $this; } public function query(Post $model) { $query = Post::where('LanguageID',$this->language)->select('posts.*'); return $this->applyScopes($query); }
then, call the dataTable manually
$('.tabPost').each(function(){ var lang_id = $(this).attr('id'); var oTable = $("#data-post" + lang_id).DataTable({ processing: true, serverSide: true, dom: 'Bfrtip', order: [[0, 'desc']], buttons: ['create', 'export', 'print', 'reset', 'reload', 'colvis', ], ajax:{ url: "{{ url("post") }}", data: function(d) { d.LanguageID = lang_id } }, columns: [ { data: 'id', name: 'id'}, { data: 'PostDate', name: 'PostDate'}, { data: 'PostTitle', name: 'PostTitle' }, { data: 'PostSlug', name: 'PostTitle' }, { data: 'action', name: 'action'} ] }); $('#'+lang_id).on('click', function(e){ oTable.draw(); e.preventDefault(); }); });
and don’t forget to set your controller like this
public function index(PostDataTable $dataTable, Request $request) { $languages = Language::where('IsActive', 1)->get(); return $dataTable->language($request->input('LanguageID'))->render('pages.back-end.lists.post', compact('languages')); }