Search record in a relationship in Laravel example

In this tutorial, I will give you an example of “Search record in a relationship in Laravel”, so you can easily apply it to your Laravel 5, Laravel 6, Laravel 7, Laravel 8, Laravel 9, and Laravel 10 applications.

First, what we’re doing here, This is the example :

Search record in a relationship in Laravel

Laravel eloquent search on fields of the related model

We have two tables: the first one is student, and the second one is student details. In the list.blade.php file, we fetched records from the student details table connected with the student’s table.

Now, we implement a search query that searches in the students and students_details tables and fetches records from both tables.


namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class StudentDetail extends Model
    use HasFactory;

    public function studentData()
        return $this->hasOne(Student::class, 'id','student_id');
<div class="row justify-content-end">
   <div class="col-lg-4">
      <div class="">
         <input wire:model="searchTerm" type="text" placeholder="Search by keyword...">


namespace App\Http\Livewire\Admin\CelebrityUser;

use App\Models\StudentDetail;
use Livewire\Component;

class ListCelebrity extends Component
   public $searchTerm = null;
   protected $queryString = ['searchTerm' => ['except' => '']];

   public function render()
      $student = StudentDetail::with('studentData')
         ->whereHas('studentData', function ($q) {
            $q->where('name', 'like', '%'.$this->searchTerm.'%');
            $q->orWhere('roll_no', 'like', '%'.$this->searchTerm.'%');
            $q->orWhere('email', 'like', '%'.$this->searchTerm.'%');
            $q->orWhere('phone', 'like', '%'.$this->searchTerm.'%');
            $student = StudentDetail::get();
      return view('livewire.admin.list-student',['student' => $student])->extends('');

I hope that this article helped you learn how to Search on Eloquent Relationships in Laravel. You may also want to check out our guide on How to find the id in comma-separated values in Laravel.

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress.

Scroll to Top