Laravel-datatables: Service implementation: sending variable via route to function query()

Created on 19 Aug 2016  路  4Comments  路  Source: yajra/laravel-datatables

Sending variable via route to function query() using service implementation

Can't get a variable inside function query() and use it.

Route:

Route::get('posts/{category_id}', ['as' => 'post', 'uses' => 'PostController@index']);

PostController:

public function index(PostsDataTable $dataTable, $category_id)
{
    return $dataTable->render('dashboard.posts.index', ["category_id" => $category->id]);
}

PostsDataTable.php

Builder Parametres:

protected function getBuilderParameters()
{
    return [
        'order' => [0,'desc'],
        'lengthMenu' => [10,25,50],
        'ajax' => ['category_id' => $category_id],   //doesn't work
    ];
}

Query:

protected function query()
{
    $query = Post::query()
        ->join('categories', 'categories.id', '=', 'posts.category_id')
        ->where('posts.category_id', $this->request()->get('category_id')) //doesn't work
        ->select([
            'posts.id', 'categories.name', 'title', 'published', 'published_at', 'published_by'
        ]);

    return $this->applyScopes($query);
}

Problems

  • Can't pass variable to the postsDataTable.php
  • Even if it is passed, can't use this variable at the function query()

    I have done it already by writing simple javascript at the view using method ajax:

        ajax: {
            url: 'myRoute',
            data: {"category_id": '{{$category_id}}'},
            type: "POST"
        },

I am looking for the way to pass variable: category_id to postsDataTable without using javascript and use this variable at the function query().

Most helpful comment

This is how I do it on my project. Just add a method on your dataTable class like ->forCategory($cat) setter.

return $dataTable->forCategory($cat)
    ->render('dashboard.posts.index', ["category_id" => $category->id]);

DataTable class:

protected $category;

public function forCategory($cat) {
    $this->category = $cat;
    return $this;
}

All 4 comments

This is how I do it on my project. Just add a method on your dataTable class like ->forCategory($cat) setter.

return $dataTable->forCategory($cat)
    ->render('dashboard.posts.index', ["category_id" => $category->id]);

DataTable class:

protected $category;

public function forCategory($cat) {
    $this->category = $cat;
    return $this;
}

Thank you, it worked!

Just what I was looking for!

For access to value?

public function query()
{
    $categ = $this->category      
}
Was this page helpful?
0 / 5 - 0 ratings