My original delete syntax was as follow for every row in the table
...
<td class="row" style="text-align: right;">
<a href="{{route('project.edit',$project->id)}}">
<i class="fas fa-cog"></i>
</a>
<form action="{{ route('project.destroy',$project->id) }}" method="POST">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger"
onclick="return confirm('Are You Sure Want to Delete?')"
style="padding: .0em !important;font-size: xx-small;">X</a>
</form>
</td>
...
I follow this guide: https://www.positronx.io/laravel-datatables-example/
and my resulting code in my controller looks like this:
...
public function index(Request $request)
{
if ($request->ajax()) {
$data = Project::latest()->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('contractor', function ($row) {
$x = $row->contractor->first_name . ' ' . $row->contractor->last_name . ' (' . $row->contractor->company->name . ')';
return $x;
})
->addColumn('action', function ($row) {
$btn = '<a href="javascript:void(0)" class="edit btn btn-success btn-sm">Edit</a> <a href="javascript:void(0)" class="delete btn btn-danger btn-sm">Delete</a>';
$x = '
<a href="{{route(\'project.edit\',$row->id)}}">
<i class="fas fa-cog"></i>
</a>
<form action="{{ route(\'project.destroy\',' . $row->id . ') }}" method="POST">
@csrf
@method(\'DELETE\')
<button type="submit" class="btn btn-danger"
onclick="return confirm(\'Are You Sure Want to Delete?\')"
style="padding: .0em !important;font-size: xx-small;">X</a>
</form>
';
return $x;
})
->rawColumns(['action'])
->make(true);
}
return view('project.index');
}
...
and my script in my index is as follows:
...
<script type="text/javascript">
$(function () {
var table = $('.yajra-datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('project.index') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'project_address', name: 'project_address'},
{data: 'owner', name: 'owner'},
{data: 'contractor', name: 'contractor'},
{
data: 'action',
name: 'action',
orderable: true,
searchable: true
},
]
});
});
</script>
...
and my datatable section is as follows:
...
<div class="col-md-12">
<div class="card">
{{-- <h2 class="mb-4">Laravel 7 Yajra Datatables Example</h2> --}}
<table class="table table-bordered yajra-datatable">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Project Address</th>
<th>Owner</th>
<th>Contractor</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
...
It all works well except that my ACTION column displays "@CSRF" and "@METHOD" and my links don't work.
I can't understand what i'm doing wrong.