1

I'm using server-side DataTables in Laravel (Yajra to be specific).

I have a route set up that pulls all assets and returns as a DataTable, but what I need is to pull all assets where the school_id is equal to the parameter in the URL.

So my application should look like this:

  • User lands on /schools/{school_id}/assets .e.g schools/1/assets
  • Datatables pulls all school's assets using that {school_id}

I'm using the following so far in the script:

$(function() {
    $('#assets-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: '/api/assets',
        columns: [
            {data: 'asset_tag', name: 'assets.asset_tag'},
            {data: 'name', name: 'assets.name'},
        ]
    });
});

What would be the best approach to fetching that ID in the URL and passing it to that ajax request?

2 Answers 2

1

This answer will reflect a method I use to have all files structured and don't mix blade files with js.

In your controller you will have the the {school_id}. You could simply pass it to the blade as so:

return view('...')->with([
  'school_id' => $school_id
]);

Create a simple input field to be able to fetch the data.

<input type="hidden" data-fetch-route="{{ route('name_of_route', ['school_id' => $school_id]) }}" id="schoolFetch">

In the .js file you can have:

$(function() {
 $('#assets-table').DataTable({
    processing: true,
    serverSide: true,
    ajax: $("#schoolFetch").attr('data-fetch-route'),
    columns: [
        {data: 'asset_tag', name: 'assets.asset_tag'},
        {data: 'name', name: 'assets.name'},
    ]
});

As you could see you will have route('name_of_route', ['school_id' => $school_id]) which means you will need to accept a parameter at the route name_of_route

If you would like to go even deeper and cleaner you can create a file called utilities.js and this file will have all the functions that you may use all over your application as such:

window.getRoute = function($element, action){
  return $element.attr('data-' + action + '-route');
}

and

ajax: $("#schoolFetch").attr('data-fetch-route'),

will turn into

ajax: getRoute($("#schoolFetch"), 'fetch'),
Sign up to request clarification or add additional context in comments.

Comments

0
$(function() {
    $('#assets-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {{ route('name.your.route.here') }},
        columns: [
            {data: 'asset_tag', name: 'assets.asset_tag'},
            {data: 'name', name: 'assets.name'},
        ]
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.