Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Search on Eloquent Relationships in Laravel

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.


<?php

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...">
      </div>
      </div>
</div>

<?php

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()
   {
      if($this->searchTerm){
         
      $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.'%');
         })->get();
         }
         else{
            $student = StudentDetail::get();
      }
      return view('livewire.admin.list-student',['student' => $student])->extends('layouts.admin.app');
    }
}

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.