I'm having an issue with the laravel's datatables plugin, when I'm trying to delete an element from my datatables list it calls a show method, making the delete impossible. Can someone explain me why it behaves like that and how to fix it ? Here is my code.
Controller :
public function destroy($project) {
$project = Project::find($project);
$project->delete();
session()->flash('message', 'projet supprimé');
return redirect()->back();
}
public function ajaxListing() {
$projects = Project::select(['id', 'title']);
return Datatables::of($projects)
->addColumn('action', function ($project) {
return '<a class="data-action" href="'.route('projects.edit', $project->id).'">
<i class="fa fa-pencil-square-o fa-2x" aria-hidden="true"></i></a>
<a class="data-action" href="'.route('projects.destroy', $project->id).'">
<i class="fa fa-times fa-2x" aria-hidden="true"></i></a>';
})
->make(true);
}
View :
<table class="table table-bordered table-striped dataTable" id="listingProjects">
<thead>
<th>ID</th>
<th>Titre</th>
<th>Actions</th>
</thead>
</table>
#push('scripts')
<script>
$(document).ready(function () {
$('#listingProjects').DataTable({
processing: true,
serverSide: true,
ordering: true,
language: {
processing: "Traitement en cours...",
search: 'Recherche : ',
lengthMenu: "Afficher _MENU_ éléments",
info: "Affichage de l'élement _START_ à _END_ sur _TOTAL_ éléments",
paginate : {
first : '<i class="fa fa-fast-backward" aria-hidden="true"></i>',
previous : '<i class="fa fa-chevron-circle-left" aria-hidden="true"></i>',
next : '<i class="fa fa-chevron-circle-right" aria-hidden="true"></i>',
last: '<i class="fa fa-fast-forward" aria-hidden="true"></i>',
}
},
ajax: '{!! route('datatables.projectData') !!}',
columns: [
{data: 'id', name: 'id'},
{data: 'title', name: 'title'},
{data: 'action', name: 'action', orderable: false, searchable: false}
]
});
});
</script>
#endpush
Routes :
Route::any('project-data', 'Admin\ProjectsController#ajaxListing')->name('datatables.projectData');
Route::resource('projects', 'Admin\ProjectsController');
I finally found the answer, the problem was in the route, we need to add an except to the resource route and create our own delete route, like that :
Route::get('projects/{project}/delete', 'Admin\ProjectsController#destroy')->name('projects.destroy');
Route::resource('projects', 'Admin\ProjectsController', ['except' => 'destroy']);
That way we just need to call the route on the link in the view.
Related
I use DataTables in Laravel and after creating 50000 records I have this error:
DataTables warning: table id=employee_table - Ajax error. For more information about this error, please see http://datatables.net/tn/7
It used to work fine when I had 200 records, but now it throws this error. How can it be fixed?
My script:
$(document).ready(function() {
var table = $('.employee_datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('admin.employees.index') }}",
columns: [
{data: 'image_path', name: 'image_path', orderable: false, searchable: false},
{data: 'name', name: 'name'},
{data: 'position', name: 'position'},
{data: 'recruitment_date', name: 'recruitment_date'},
{data: 'phone_number', name: 'phone_number'},
{data: 'email', name: 'email'},
{data: 'payment', name: 'payment', render: $.fn.dataTable.render.number( ',', '.', 3, '$')},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
});
Index function to call the DataTable:
public function index(Request $request)
{
if ($request->ajax()) {
$data = Employee::with('position')->select('id','name','email', 'position_id', 'image_path', 'recruitment_date',
'phone_number', 'payment')->get();
return Datatables::of($data)->addIndexColumn()
->addColumn('position', function (Employee $employee) {
return $employee->position->name;
})->addColumn('image_path', function ($data) { $url=asset("images/$data->image_path");
return '<img src='.$url.' class="rounded-circle" width="40" align="center" />'; })
->addColumn('action', function($data){
$button = ' <i class="fas fa-fw fa-edit"></i>Edit';
$button .= ' <button type="button" name="edit" id="'.$data->id.'" class="delete btn btn-danger btn-sm"">
<i class="fas fa-fw fa-trash"></i> Delete</button>';
return $button;
})->rawColumns(['image_path', 'action'])
->make(true);
}
return view('admin.employees.index');
}
It was indeed because of get() so now my index function looks like this:
$data = Employee::with('position')->select('id','name','email', 'position_id', 'image_path', 'recruitment_date',
'phone_number', 'payment');
Thanks to Manjeet Barnala.
I am developing a Laravel management application with Yajra datatables.
So I have various tables, and in particular in the user table I need to change the user's status (active / inactive) via ajax request by simply clicking a button or ticking a checkbox.
This is my first time using ajax and datatables, and I have no idea how to achieve this ... is it possible or are there better / quicker ways to do this?
I accept any advice or suggestion
My code:
controller
<?php
namespace Modules\User\Http\Controllers;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Models\User;
use DataTables;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
/**
* Display a listing of the resource.
* #return Renderable
*/
public function index(Request $request)
{
$user = User::select('id', 'name', 'email', 'attivo' , 'email_verified_at', 'created_at')->get();
if($request->ajax()){
return Datatables::of($user)
->addIndexColumn()
->addColumn('stato', function($row){
($row['attivo'] == 1 ) ? $btn1 = '<div class="btn-group" role="group" aria-label="Basic example"><a href="#" id="btn-post" dusk="postButton" class="btn btn-primary" role="button" data-toggle="modal" data-target="#addPost" style="color:white; font-size:small;">
<span class="ion-plus-circled"> Disattiva</span>
</a>'
: $btn1 = '<div class="btn-group" role="group" aria-label="Basic example"><button id="btnAttiva" class="btn btn-primary btn-rounded" style="color:white; font-size:small;">Attiva</button>';
return $btn1;
})
->addColumn('action', function($row){
$btn = '<div class="btn-group" role="group" aria-label="Basic example">View</div>';
$btn = $btn.'Edit';
$btn = $btn.'<form action="/user/delete" method="POST"><input type="hidden" name="_token" value="{{ #csrf() }}"><input type="hidden" name="_method" value="{{ #method(\'delete\') }}">
<input type="hidden" class="form-control" name="idu" value="'.$row['id'].'"><input type="submit" class="edit btn btn-danger btn-rounded" style="color:white; font-size:small;" value="Delete" /></form></div>';
return $btn;
})
->rawColumns(['action', 'stato'])
->make(true);
}
return view('user::index');
}
public function setState(Request $request){
// here i need to modify the user state
}
}
view:
#extends('layouts.master')
#section('title', 'Lista Utenti')
#section('content')
#if (\Session::has('error'))
<div class="alert alert-danger">
<ul>
<li>{!! \Session::get('error') !!}</li>
</ul>
</div>
#endif
#if (\Session::has('success'))
<div class="alert alert-success">
<ul>
<li>{!! \Session::get('success') !!}</li>
</ul>
</div>
#endif
<div class="col-lg-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Utenti</h4>
<p class="card-description">
Lista degli utenti registrati
</p>
<div class="table-responsive">
<table class="table table-bordered" id="dtUserList">
<thead>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Email Verificata</th>
<th>Stato</th>
<th>Created</th>
<th>Action</th>
</thead>
</table>
</div>
</div>
</div>
</div>
<div>
<a href="{{ url('/user/create') }}" class="btn btn-primary btn-rounded"
style="color:white; font-size:small;">Aggiungi utente</a>
</div>
#endsection
#section('script')
<script>
$(function() {
var table = $('#dtUserList').DataTable({
processing: true,
serverSide: true,
ajax: '{{ url('user') }}',
columns: [
{ data: 'id', name: 'id', visible: false },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'email_verified_at', name: 'email_verified_at'},
{ data: 'stato', name: 'stato', orderable: false, searchable: false},
{ data: 'created_at', name: 'created_at' },
{ data: 'action', name: 'action', orderable: false, searchable: false },
],
order: [[0, 'asc']]
});
});
</script>
#endsection
EDITED CODE WITH AJAX CALL:
view index.blade.php
#extends('layouts.master')
#section('title', 'Lista Utenti')
#section('content')
#if (\Session::has('error'))
<div class="alert alert-danger">
<ul>
<li>{!! \Session::get('error') !!}</li>
</ul>
</div>
#endif
#if (\Session::has('success'))
<div class="alert alert-success">
<ul>
<li>{!! \Session::get('success') !!}</li>
</ul>
</div>
#endif
<div class="col-lg-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Utenti</h4>
<p class="card-description">
Lista degli utenti registrati
</p>
<div class="table-responsive">
<table class="table table-bordered" id="dtUserList">
<thead>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Email Verificata</th>
<th>Stato</th>
<th>Created</th>
<th>Action</th>
</thead>
</table>
</div>
</div>
</div>
</div>
<div>
<a href="{{ url('/user/create') }}" class="btn btn-primary btn-rounded"
style="color:white; font-size:small;">Aggiungi utente</a>
</div>
#endsection
#section('script')
<script type="text/javascript">
$(function() {
var table = $('#dtUserList').DataTable({
processing: true,
serverSide: true,
ajax: '{{ url('user') }}',
columns: [
{ data: 'id', name: 'id', visible: false },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'email_verified_at', name: 'email_verified_at'},
{ data: 'stato', name: 'stato', orderable: false, searchable: false},
{ data: 'created_at', name: 'created_at' },
{ data: 'action', name: 'action', orderable: false, searchable: false },
],
order: [[0, 'asc']]
});
});
$.fn.myFunction = function(form){
//put the form elements in an array
id = $(form).serializeArray();
//Get the value of the first index(the id)
iduser = id[0]['value'];
idstato = id[1]['value'];
$.ajax({
// Post method
type: 'POST',
// Url to the route
url: "{{ url('/user/deactivate') }}",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
// Data to submit to the function
data: {
//CRSF token for laravel form validations
_token: $('meta[name="csrf-token"]').attr('content'),
idu: iduser,
ids: idstato
},
success: function(response){
//if request is made successfully then the response represent the data
$( "#result" ).empty().append( response );
}
});
}
</script>
#endsection
Controller:
<?php
namespace Modules\User\Http\Controllers;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Models\User;
use DataTables;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
/**
* Display a listing of the resource.
* #return Renderable
*/
public function index(Request $request)
{
$user = User::select('id', 'name', 'email', 'attivo' , 'email_verified_at', 'created_at')->get();
if($request->ajax()){
return Datatables::of($user)
->addIndexColumn()
->addColumn('stato', function($row){
($row['attivo'] == 1 ) ? $btn1 = '<form><input type="hidden" name="user" value="'.$row['id'].'"><div class="form-group"><select onchange="$.fn.myFunction(this.form)" name="stato"><option value="0">Disattivo</option><option value="1" selected>Attivo</option></select></div></form>'
: $btn1 = '<form><div class="form-group"><input type="hidden" name="user" value="'.$row['id'].'"><select name="stato" onchange="$.fn.myFunction(this.form)"><option value="0" selected>Disattivo</option><option value="1">Attivo</option></select></div></form>';
return $btn1;
})
->addColumn('action', function($row){
$btn = '<div class="btn-group" role="group" aria-label="Basic example">View</div>';
$btn = $btn.'Edit';
$btn = $btn.'<form action="/user/delete" method="POST"><input type="hidden" name="_token" value="{{ #csrf() }}"><input type="hidden" name="_method" value="{{ #method(\'delete\') }}">
<input type="hidden" class="form-control" name="idu" value="'.$row['id'].'"><input type="submit" class="edit btn btn-danger btn-rounded" style="color:white; font-size:small;" value="Delete" /></form></div>';
return $btn;
})
->rawColumns(['action', 'stato'])
->make(true);
}
return view('user::index');
}
public function disattiva($idu, $ids){
dd($idu+":"+$ids);
}
}
My Route:
//rotte USER module with CRUD route
Route::middleware(['auth'])->prefix('user')->group(function() {
Route::get('/', 'UserController#index'); //dashboard -> lista utenti
Route::post('/deactivate', 'UserController#disattiva');
Route::get('/detail/{idu}', 'UserController#show'); // dettaglio specifico utente
Route::get('/edit/{idu}', 'UserController#showEditForm'); // form edit utente con dato idu
Route::patch('/edit', 'UserController#edit'); // scrivere le modifiche sul DB
Route::delete('/delete', 'UserController#destroy'); // eliminare utente dal DB
Route::get('/create', 'UserController#showCreateForm'); // form creazione nuovo utente
Route::post('/create', 'UserController#create'); // creare l'utente sul DB
Route::get('/profile', 'UserController#showProfile'); // mostra il profilo dell'utente loggato
});
Create a form inside your table and create a custom function in the select
(I assume you want to change it using a select)
<select onchange="$.fn.myFunction(this.form)">
After that you want to create a ajax request like this:
$.fn.myFunction = function(form){
//put the form elements in an array
id = $(form).serializeArray();
//Get the value of the first index(the id)
id = id[0]["value"];
$.ajax({
// Post method
type: 'POST',
// Url to the route
url: "/ajax/myfunction",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
// Data to submit to the function
data: {
//CRSF token for laravel form validations
_token: $('meta[name="csrf-token"]').attr('content'),
id: id
},
success: function(response){
//if request is made successfully then the response represent the data
$( "#result" ).empty().append( response );
}
});
}
I'm getting an error when trying to setup a datatables with my laravel project.
DataTables warning: table id=DataTables_Table_0 - Ajax error. For more information about this error, please see http://datatables.net/tn/7
This is my controller.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Transaction;
use DataTables;
use Illuminate\Support\Facades\DB;
class TestTableController extends Controller
{
public function index()
{
return view('testtable');
}
public function getTestTable(Request $request)
{
if ($request->ajax()) {
$data = DB::table('transactions')->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$actionBtn = 'Edit Delete';
return $actionBtn;
})
->rawColumns(['action'])
->make(true);
}
}
}
This my route.
Route::get('testtable', [TestTableController::class, 'index']);
Route::get('testtable/list', [TestTableController::class, 'getTestTable'])->name('testtable.list');
View/blade.
<body>
<div class="container mt-5">
<h2 class="mb-4">Laravel 7|8 Yajra Datatables Example</h2>
<table class="table table-bordered yajra-datatable">
<thead>
<tr>
<th>ID</th>
<th>Amount</th>
<th>Charge</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js">
</script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js">
</script>
<script type="text/javascript">
$(function () {
var table = $('.yajra-datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('testtable.list') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'amount', name: 'amount'},
{data: 'charge', name: 'charge'},
{
data: 'action',
name: 'action',
orderable: true,
searchable: true
},
]
});
});
</script>
This is the error from laravel debugbar.
But the query did have results.
This is the output if I echo the query.
$data = DB::table('transactions')->get();
echo $data;
Anything else I'm missing? The exact same code is working if I tested in a new fresh laravel installation. This is an existing project that I try to implement datatables. I guess there must be something from current project configuration that causing the issue.
Your code in getTestTable function look fine. You got in the debugbar:
No query results for model [App\Frontend] testtable
But the code in getTestTable has nothing related to testtable so I guess route('testtable.list') doesn't get to that function. And the reason may be because you put a route like Route::get('testtable/{id}',... before Route::get('testtable/list', so when you call testtable/list, it will take list as id and go to other function.
If my guess is true, you can fix it by putting testtable/list before testtable/{id} route.
I share full details with Sample Code from my Project, this below Example code is a Manage Role DataTable from my project. please refer step by step & try to understand it.
first of all you need to install Laravel Yajra DataTable using below Composer command
composer require yajra/laravel-datatables-oracle
then after Define Routes in web.php as like my sample code
Route::get('/', [\App\Http\Controllers\Admin\RoleController::class, 'index'])->name('admin.roles.index'); //index all the data view...
Route::post('/', [\App\Http\Controllers\Admin\RoleController::class, 'getIndexUsers'])->name('admin.roles.getIndexRoles'); //Get Users for Laravel Yajra Datatable Index Page record...
then after create view file for it, I share sample from my project
<div class="card-body">
<table id="role_table" class="table table-bordered table-striped w-100">
<thead>
<tr>
<th>No.</th>
<th>Role Name</th>
<th>Role Slug</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>No.</th>
<th>Role Name</th>
<th>Role Slug</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.card-body -->
& in Footer Script define Function for Initialize the DataTable like below,
<script type="text/javascript">
var dataTable = $('#role_table').DataTable({
lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
processing: true,
serverSide: true,
order: [],
searchDelay: 500,
"scrollX": "auto",
"responsive": true,
// "lengthChange": false,
"autoWidth": true,
ajax: {
url: '{{ route("admin.roles.getIndexRoles")}}',
type: 'post',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: function (data) {
// data.fromValues = $("#filterUserType").serialize();
},
},
columns: [
{data: 'SrNo', //try with data: 'SrNo' OR data: 'id',
render: function (data, type, row, meta) {
// return meta.row + meta.settings._iDisplayStart + 1;
return meta.row + 1;
}, searchable: false, sortable: false
},
{data: 'role_name', name: 'role_name'},
{data: 'role_slug', name: 'role_slug'},
{data: 'action', name: 'action', searchable: false, sortable: false},
],
});
</script>
then after In your Controller load Yajra DataTable Class for use it
use Yajra\DataTables\DataTables; //for Laravel DataTable JS...
Now, create Function for Display View File like this,
public function index()
{
return view('admin.roles.index');
}
Now I crated Function method for Ajax Request for DataTable Initialize
public function getIndexUsers(Request $request)
{
$roles = Role::select('roles.*');
if($request->order ==null){
$roles->orderBy('id', 'desc');
}
$detail_data = $roles;
return Datatables::of($detail_data)
->addColumn('action', function ($data) {
return $this->DataTableAction($data);
})
->rawColumns(['action'])
->make(true);
}
public function DataTableAction($data){
$btn = '<div class="btn-group">';
if($data->id == "1" || $data->id == "2"){
$btn .= '<button type="button" class="btn btn-danger dropdown-toggle ml-2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" disabled>Action
</button>';
}else{
$btn .= '<button type="button" class="btn btn-danger dropdown-toggle ml-2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Action
</button>';
}
$btn .= '<div class="dropdown-menu">';
$btn .= '<a class="dropdown-item" href="'.route('admin.roles.edit',$data->id).'" style="color: black;" onmouseover=\'this.style.background="#dee2e6"\' onmouseout=\'this.style.background="none"\'><i class="far fa-edit text-primary"></i> Edit</a>';
$btn .= '<div class="dropdown-divider"></div>';
$btn .= '<a role_id="'.$data->id.'" class="dropdown-item deleteRole" href="#" style="color: black;" onmouseover=\'this.style.background="#dee2e6"\' onmouseout=\'this.style.background="none"\'><i class="far fa-trash-alt text-danger"></i> Delete</a>';
$btn .= '</div>
</div>';
return $btn;
}
Important Note:- Currently I use Laravel 8 So, It's not necessary to needs to define Yajra Service Provider Class in config/app.php . But if you are getting any error in your different Laravel version then you wil needs to define Yajra Service Provider Class in config/app.php... for define it follow below steps
**
Note that, below step not compulsory, its depends on your Laravel
version
**
config/app.php
.....
'providers' => [
....
Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
....
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....
then Run below Command
php artisan optimize
then if you get any problem, try to Clear Cache using
php artisan cache:clear
Important Note:- If you define Service Provider Class in config/app.php & run optimize command, then May be Laravel will load it in autoload which is automatically called when your code references a class or interface that hasn't been loaded yet, I'm not sure
if everything is ok in the app codes,
you may loosed config for yajra..
so to configure it, you can go to the config folder in the app root directory and then open app.php file from there and add this line to the provider..
Yajra\DataTables\DataTablesServiceProvider::class
the result will be something like this:
'providers' => [
..
..
..
Yajra\DataTables\DataTablesServiceProvider::class,
]
and also add this line to the aliases:
Yajra\DataTables\Facades\DataTables::class
try like this:
'aliases' => [
..
..
..
..
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
finally, save the file(config\app.php) like above and then open up cmd or terminal and try to clear the app cached file(that includes the config cache) using the fallowing command:
php artisan optimize
I use this component in my project: yajra/laravel-datatables
I have controller:
public function dataTable(Request $request)
{
if ($request->ajax()) {
return Datatables::of($this->model->all())
->addIndexColumn()
->editColumn('enable', function ($row) {
if ($row->enable == 1)
return '<span class="label font-weight-bold label-lg label-light-success label-inline">aktywny</span>';
else return '<span class="label font-weight-bold label-lg label-light-danger label-inline">nieaktywny</span>';
})
->editColumn('name', function ($row) {
return Str::limit($row->name, 80, '...');
})
->addColumn('action', function ($row) {
$btn = '<i class="far fa-edit"></i> ';
$btn .= '<i class="removeItem far fa-trash-alt"></i> ';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
}
and html:
<table class="table table-bordered data-table ">
<thead>
<tr class="resources">
<th>ID</th>
<th>Nazwa produktu</th>
<th>Status</th>
<th width="100px" class="text-center">Akcja</th>
</tr>
</thead>
<tbody class="data-table-center">
</tbody>
</table>
</div>
<div class="datatable datatable-bordered datatable-head-custom" id="kt_datatable"></div>
$(function () {
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('product.dataTable') }}",
language: {
url: "{{ asset('js/lang/Polish.json') }}"
},
iDisplayLength: 50,
render: function (data, type, row) {
return data;
},
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
// {data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'enable', name: 'enable'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
});
In the status (enable) column I see this html instead of the final string. As if a blade would replace such html badly.
My result:
<span class="label font-weight-bold label-lg label-light-success label-inline">aktywny</span>
Prview: https://ibb.co/6tXdH65
How can I fix it?
just add enable in your action in dataTable function
->rawColumns(['action','enable'])
->make(true);
This is my route
Route::get('/view/{id}', [
'uses' => 'ClientController#view',
'as' => 'view'
]);
This is my Client controller
public function view($id){
$client = Client::where('id',$id)->first();
return view('view',compact('client'));
}
This is my datatable
#extends('layouts.datatables_master')
#section('content')
<table class="table table-bordered" id="clients-table">
<thead>
<tr>
<th>ID</th>
<th>Company Name</th>
<th>Name</th>
<th>Surname</th>
<th>ID Number</th>
<th>Created</th>
<th>Last Updated</th>
<th>Actions</th>
</tr>
</thead>
</table>
#stop
#push('scripts')
<script>
$(function() {
$('#clients-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('business.list') !!}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'companyname', name: 'companyname' },
{ data: 'name', name: 'name' },
{ data: 'surname', name: 'surname' },
{ data: 'idnumber', name: 'idnumber' },
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' },
{ data: "actions",
"render": function(data, type, row) {
return '<i class="fa fa-search" title="View"></i> <i class="fa fa-pencil" data-toggle="tooltip" data-placement="top" title="Edit"></i> <i class="fa fa-trash" data-toggle="tooltip" data-placement="top" title="Delete"></i>'
;}
}
]
});
});
</script>
#endpush
Problem
My Main issue is passing an ID for all users. If you check my render function on my DataTable I said return route(view,1) where it's 1. I want to pass $id but it says undefined variable. Please help.
You could return the generated route link from your controller like:
return datatables(Client::query())
->addColumn('actions', function ($client) {
return [
'edit_link' => route('view', [$id => $client->id]),
];
})->toJson();
and render in your view as
{
data: "actions",
render: function(data, type, row) {
return
'<a href="' + data.edit_link + '" class="btn btn-xs btn-info">' +
'<i class="fa fa-search" title="View"></i></a>' +
'<a href="#" class="btn btn-xs btn-primary">' +
'<i class="fa fa-pencil" data-toggle="tooltip" data-placement="top" title="Edit"></i>' +
'</a>' +
'<a href="#" class="btn btn-xs btn-danger">' +
'<i class="fa fa-trash" data-toggle="tooltip" data-placement="top" title="Delete"></i>' +
'</a>';
}
}
the value of data should be an 'id', and use url() instead of route() :
{ data: "id",
"render": function(data, type, row) {
return '<a href="{{ url("view") }}/"'+ data +'>View</a>';
}
}
Try like this
return '<i class="fa fa-search" title="View"></i>
You pass the client variable to blade
{{ route('view',$client->id); }}