I'm getting this error in DataTables: DataTables warning: table id=DataTables_Table_0 - Exception message:
Attempted to read null property "name".
Although each position_id has an id in the position table, so it should not be empty. If anyone would like to help I would be grateful. My model:
public function position() { return $this->belongsTo(Position::class); }
My controller:
class EmployeeController extends Controller { public function index(Request $request) { if ($request->ajax()) { $data = Employee::with('position')->select('id','name','email')->get(); return Datatables::of($data)->addIndexColumn() ->addColumn('position', function (Employee $employee) { return $employee->position->name; })->addColumn('action', function($data){ $button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm"> <i class="bi bi-pencil-square"></i>Edit</button>'; $button .= ' <button type="button" name="edit" id="'.$data->id.'" class="delete btn btn-danger btn-sm"> <i class="bi bi-backspace-reverse-fill"></i> Delete</button>'; return $button; }) ->make(true); } return view('admin.employees.index'); } }
script:
$(document).ready(function() { var table = $('.user_datatable').DataTable({ processing: true, serverSide: true, ajax: "{{ route('admin.employees.index') }}", columns: [ {data: 'id', name: 'id'}, {data: 'name', name: 'name'}, {data: 'email', name: 'email'}, {data: 'position', name: 'position.name'}, {data: 'action', name: 'action', orderable: false, searchable: false}, ] });
migrate:
public function up() { Schema::create('employees', function (Blueprint $table) { $table->id(); $table->string('name'); $table->foreignId('position_id')->nullable(); $table->string('phone_number'); $table->date('recruitment_date'); $table->string('email')->unique(); $table->string('image_path')->nullable(); $table->string('payment'); $table->timestamps(); $table->string('admin_created_id')->nullable(); $table->string('admin_updated_id')->nullable(); }); }
This error means that when the Datatable tries to get data from
$data
, there is no collection or array to locate it inside theget()
methodSo when you look at
$raw
the above returns no position or attributesFrom that point on, we will change the controller to look like this
If that doesn't work, you can try changing the database query But for this I need to dump $data You can see the result in the Network section of the Inspect element in your browser
dd($data);
The problem is because of choice. It seems that if you want to use relations you have to add a foreign key to the select (in my case "position_id"), or remove it completely and just use get . Thanks to everyone who helped in the comments.