Laravel 9 Datatables Column Relationship Search Tutorial

Laravel 9 dataTables with relationship search; Through this tutorial, we will learn how to search or filter and display column in yajra dataTables with relationships in laravel 9 apps.

Sometimes, we have more than two tables joined and want filter or search column data with separate table in laravel 9 app. So this tutorial will guide step by step how to add relationship search or filter in laravel 9 apps using dataTable js.

Laravel 9 DataTables with Relationship Search/Filter Example

Use the following steps to implement relationship search or filter in laravel 9 apps using dataTable js:

  • Step 1 – Install Laravel 9 App
  • Step 2 – Connecting App to Database
  • Step 3 – Install Yajra DataTable
  • Step 4 – Create Migration and Modal
  • Step 5 – Add route
  • Step 6 – Create Controller by Artisan Command
  • Step 7 – Create Blade File
  • Step 8 – Run Development Server

Step 1 – Install Laravel 9 App

First of all, open your terminal and execute the following command to install or download or install laravel 9 app:

composer create-project --prefer-dist laravel/laravel blog

Step 2 – Connecting App to database

After that, open “.env” file and update the database name, username and password in the env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

Step 3 – Install Yajra DataTable

In this step, execute the following command on terminal to install yajra datatable via composer package, so open your terminal and execute the following command:

composer require yajra/laravel-datatables-oracle

After that, you need to set providers and alias.

config/app.php

.....
'providers' => [
    ....
    Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
    ....
    'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....

Step 4 – Create Migration and Modal

In this step, execute the following command on the terminal to create post table migration and create Post Modal:

php artisan make:modal Post -m

database/migrations/2020_05_20_070104_create_posts_table.php

<?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');
    }
}


Now run the following command

php artisan migrate

After you have to update following code in your Post model file to create a posts table.

Next open Post.php model, which is placed inside App/models directory and create relationship in this model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;

class Post extends Model
{
	use HasFactory;

    protected $fillable = ['title'];

    public function users()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }
}


Step 5 – Add route

Next, open your “routes/web.php” file and add the following route:

use App\Http\Controllers\PostController;

Route::get('posts', [PostController::class, 'index'])->name('posts.index');

Step 6 – Create Controller by Artisan Command

In this step, open your terminal execute the following command to create PostController.php file:

php artisan make:controller PostController

This command will create PostController by the artisan command.

Next, go to app/http/controller/PostController.php. and update the following methods into your controller file:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\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 this step, Visit resources/views directory and create new file users.blade.php.

After that, update the following html and javascript code into your blade view file:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Datatables with Relationship Tutorial - Tutsmake.com</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">Laravel 9 Datatables with Relationship Tutorial - Tutsmake.com</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 Development Server

In this step, Execute the php artisan serve command on terminal to start server locally:

php artisan serve

Then open your browser and hit the following url on it:

http://127.0.0.1:8000/posts

Conclusion

Laravel 9 datatables with reletionship example, you have learned how to use relationship on dataTables and as well as how to datatables filter column on a relationship.

Recommended Laravel Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *