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

FREDERIC LD's avatar

yajra/eloquent datatable does not display anything for belongsTo relationship fields

Hi,

I have a belongs relationship I would like to display in a Yajrah datatable. I have the table working using DB but I want to get it to work using eloquent.

Working script using DB

 if ($request->ajax()) {

            $data = DB::table('log_activities')
                        ->join('admins', 'log_activities.admin_id', '=', 'admins.id')
                        ->whereIn('type', array('info'))
                        ->select(['log_activities.subject', 'log_activities.type', 'admins.first_name', 'admins.last_name', 'log_activities.created_at'])
                        ->latest();
            
            return Datatables::of($data)
                    ->addColumn('admin_name', function($row){
                        return $row->first_name.' '.$row->last_name;
                    })
                    ->setRowClass(function ($row) {
                        return $row->type; //The row class is set based on the log type 
                    })
                    ->make(true);
}

To change this for eloquent,

Migration

        Schema::create('log_activities', function (Blueprint $table) {
            $table->id(); //Alias of $table->bigIncrements('id')
            $table->string('subject', 5000);
            $table->string('url', 5000);
            $table->string('method',20);
            $table->string('ip',20);
            $table->string('agent')->nullable();
            $table->unsignedBigInteger('admin_id');
            $table->enum('type', ['info', 'notice', 'warning', 'error', 'critical', 'emergency'])->default('info');
            $table->timestamps();
        });

	Schema::table('log_activities', function($table)
        {
            $table->foreign('admin_id')->references('id')->on('admins');
        });



           Schema::create('admins', function (Blueprint $table) {
                $table->bigIncrements();
                $table->string('first_name');
                $table->string('last_name');
                $table->string('email')->unique();
                $table->timestamp('email_verified_at')->nullable();
                $table->string('password');
                $table->rememberToken();
                $table->timestamps();
                $table->softDeletes();
            });

relationship


class LogActivity extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'subject', 'url', 'method', 'ip', 'agent', 'admin_id', 'type'
    ];


    public function admin()
    {
        return $this->belongsTo(Admin::class, 'admin_id', 'id');
    }

}

controller

         
	$query = LogActivity::select(['subject', 'type', 'created_at')->with('admin:id,first_name,last_name')->get();
            
            return Datatables::of($query)
                    ->addColumn('admin_name', function($row){
                        return $row->first_name.' '.$row->last_name;
                    })
                    ->setRowClass(function ($row) {
                        return $row->type; //The row class is set based on the log type 
                    })
                    ->make(true);

view

<script>
$(function() {

    $('#logs-table').DataTable({
        paging: true, // Allow data to be paged
        searching: true, // Search box and search function will be actived
        ordering: true,

        lengthMenu: [[1, 10, 25, 50, -1], [1, 10, 25, 50, "All"]],
        pageLength: 10,

        autoWidth: true,
        
        dom: 'Blfrtip', //DOM variable for each element of the datatable
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ],

        processing: true,
        serverSide: true,

        ajax: '{!! route('admin.log.index') !!}',

        columns: [
            { data: 'subject', name: 'subject' },
            { data: 'admin_name', name: 'admin_name' },
            { data: 'created_at', name: 'created_at', orderable: false, searchable: false },
        ],

    });

});

</script>

I am not getting any error. I just get data displayed in admin_name column

In the below result, the admin relation does not return anything...

#items: array:17 [
    0 => RF\RFCmsLogs\Models\LogActivity {#1392
      #fillable: array:7 [
        0 => "subject"
        1 => "url"
        2 => "method"
        3 => "ip"
        4 => "agent"
        5 => "admin_id"
        6 => "type"
      ]
      #with: array:1 [
        0 => "admin"
      ]
      #connection: "mysql"
      #table: "log_activities"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:3 [
        "subject" => "Permission Group "Logs" has been created."
        "type" => "info"
        "created_at" => "2020-06-15 22:36:14"
      ]
      #original: array:3 [
        "subject" => "Permission Group "Logs" has been created."
        "type" => "info"
        "created_at" => "2020-06-15 22:36:14"
      ]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [
        "admin" => null
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [
        0 => "*"
      ]
    }

Any idea?

Just tried this

$records = LogActivity::all();

foreach($records as $r){
    print $r->admin->first_name;

}

and it works, so my belongsTo relationship must be properly setup...

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

In the example that you've shown and you said it works, you are accessing the first and last name of the admin through the admin relationship, while when you are using it, you try to access them as first class citizens.

Also when you use with and select you will have to provide the id which Laravel needs to use in order to make the relationship.

So try this instead:

$query = LogActivity::select(['subject', 'type', 'created_at', 'admin_id'])
    ->with('admin:id,first_name,last_name')->get();
            
return Datatables::of($query)
    ->addColumn('admin_name', function($row){
        return $row->admin->first_name.' '.$row->admin->last_name;
    })
    ->setRowClass(function ($row) {
        return $row->type; //The row class is set based on the log type 
    })
    ->make(true);

Please or to participate in this conversation.