Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Shuvoo's avatar

How to use Laravel Datatable

i want to showing datatables with By campaign_id

 public function get_leadsbyid(Request $request)
    {
        if (request()->ajax()) {
            $leads = datatables()->of(Leads::all())->toJson();
            return $leads;
        }
    }
<script type="text/javascript">
    function get_leads(){
        var campaign_id = $('#campaign_id').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#example').DataTable({
processing: true,
serverSide: true,
ajax: {
url: '{{ route('ManageLeads.get_leadsbyid') }}'  ,
type: 'GET',
},
columns: [
{data: 'id', name: 'id', 'visible': false},
{ data: 'mastermail', name: 'mastermail' },
{ data: 'fromname', name: 'fromname' },
{ data: 'serial', name: 'serial' },
{ data: 'created_at', name: 'created_at' },
],
order: [[0, 'desc']]
});
    }
$(document).ready(function(){
get_leads();
});
$('#campaign_id').on('change', function() {
get_leads();

});
>div class="form-group col-md-3">
                                <label for="group">Campaign</label>
                                <select name="campaign_id" id="campaign_id" class="form-control" required>
                                    <option>Select Campaign</option>

                                    @foreach($campaigns as $campaign)
                                    <option value="{{$campaign->id}}"> {{$campaign->name}} </option>
                                    @endforeach

                                </select>
                            </div>

0 likes
1 reply
Nakov's avatar
Nakov
Best Answer
Level 73

@shuvoo so I assume you've got Campaign model, right?

Then define your route like this:

Route::get('/leads/{campaign}', 'LeadsController@get_leadsbyid')->name('ManageLeads.get_leadsbyid');

Then in your datatable you can use this for example:

url: '/leads/' + campaign_id,

And in the controller use Route model bidning:

public function get_leadsbyid(Request $request, Campaign $campaign)
{
    dd($campaign); // here the campaign should be loaded for that ID.

    if (request()->ajax()) {
        $leads = datatables()->of(Leads::all())->toJson();
        return $leads;
    }

    return 'Some other response here';
}

Let me know if it works.

Please or to participate in this conversation.