1

In Laravel 5.4, I need to use an url instead route in a javascript file.

Right now I have a blade file with this code:

@section('after-scripts')
    {{ Html::script("https://cdn.datatables.net/v/bs/dt-1.10.15/datatables.min.js") }}
<script>
    $(function () {
        $('#users-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: '{{ route("admin.access.user.get") }}',
                type: 'post',
                data: {status: 1, trashed: false}
            },
            columns: [
                {data: 'id', name: '{{config('access.users_table')}}.id'},
                {data: 'first_name', name: '{{config('access.users_table')}}.first_name'},                ],
            order: [[0, "asc"]],
            searchDelay: 100
        });
    });
</script>

But I want to take off the blade this and save it as a normal .js file in my js assets. What should I do with the blade helpers like route()and config()?

1
  • 1
    An easy way is to output a global (namespaced) object on your page with JavaScript::put(...) Commented Jul 26, 2017 at 17:11

1 Answer 1

1

You can initialize JavaScript variables in the blade file with the output of config and route before importing the script.

In Blade Template file

@section('after-scripts')
    {{ Html::script("https://cdn.datatables.net/v/bs/dt-1.10.15/datatables.min.js") }}
    <script>
        var accessurl = '{{ route("admin.access.user.get") }}';
        var config = '{{config('access.users_table')}}';
    </script>
    <script src="{{asset('path/to/jsfile.js')}}" type="text/javascript"></script>
@endsection

In JavaScript file

$(function () {
    $('#users-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: accessurl,
            type: 'post',
            data: {status: 1, trashed: false}
        },
        columns: [
            {data: 'id', name: config + '.id'},
            {data: 'first_name', name: config +'.first_name'},],
        order: [[0, "asc"]],
        searchDelay: 100
    });
});
Sign up to request clarification or add additional context in comments.

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.