How to Display Relationship Data into Yajra Datatables?

I can help you write a step-by-step guide on how to display relationship data using Yajra DataTables in Laravel. Yajra DataTables is a powerful package that allows you to create interactive and feature-rich data tables. In this guide, we'll focus on displaying data from Eloquent model relationships within DataTables.

When building data tables for your Laravel application, you often encounter situations where you need to display related data from Eloquent model relationships. Yajra DataTables, a popular package for creating dynamic and interactive tables, can help you achieve this effortlessly.

In this step-by-step guide, we'll explore how to display relationship data using Yajra DataTables in Laravel 9/10.

So, let's see how to display relationship data into yajra datatables, yajra datatables with relationship laravel 10, laravel 10 yajra datatables, eager loading relationships.

Step 1: Install Laravel 10

In this step, we will install laravel 10 using the following composer command.

composer create-project --prefer-dist laravel/laravel datatable-example

 

Step 2: Setup Database Configuration

Configure Database connection in .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_username
DB_PASSWORD=database_password

 

Step 3: Install Yajra DataTable

Install the Yajra DataTables package using the following composer command.

composer require yajra/laravel-datatables-oracle

 

Step 4: Create Migration and Modal

Now, we will create migration and modal using the following command.

php artisan make:modal Post -m

Migration:

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id');
            $table->string('title');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Migrate the table to the database using the following command.

php artisan migrate

Open the Post.php model and modify the following changes.

app/Models/Post.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;
class Post extends Model
{
    protected $fillable = ['title'];
    
    public function users()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }
}


 

 

Step 5: Create a Route

Next, open your routes/web.php file and add the following routes.

Route::get('posts','PostController@index')->name('posts.index');

 

Step 6: Create Controller

Now, we will create a controller using the following command.

php artisan make:controller PostController

PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Post;
use DataTables;
class PostController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $model = Post::with('users');
                return DataTables::eloquent($model)
                ->addColumn('users', function (Post $post) {
                    return $post->users->name;
                })
                ->toJson();
        }
        return view('users');
    }
}

 

Step 7: Create Blade File

In your Blade view, include the DataTable HTML with the defined route and JavaScript to initialize the table.

<!DOCTYPE html>
<html>
<head>
    <title>How to Display Relationship Data into Yajra Datatables? - Techsolutionstuff</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <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.16/js/jquery.dataTables.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
    <style type="text/css">
        .paginate_button{
            padding: 0px !important;
        }
    </style>
</head>
<body>
<div class="container" style="margin-top: 100px;margin-bottom: 100px; ">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header bg-info text-white">How to Display Relationship
Data into Yajra Datatables? - Techsolutionstuff</div>
                <div class="card-body">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif
                     <table class="table table-bordered data-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Title</th>
                                <th>Auther</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
   $(document).ready(function() {
        $('.data-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: "{{ route('posts.index') }}",
            columns: [
                {data: 'id', name: 'id'},
                {data: 'title', name: 'title'},
                {data: 'users', name: 'users.name'},
            ]
        });
    });
</script>
</body>
</html>

 

Step 8: Run the Laravel Application

Now, run the laravel application using the following command.

php artisan serve

 

Conclusion:

By following these steps, you can seamlessly display related data from Eloquent model relationships in Yajra DataTables within your Laravel application. This powerful combination allows you to create interactive data tables that present complex relationships with ease.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS