user11438001
user11438001

Reputation:

How to Search with id has relation with another column in laravel?

The idea is that I have two tables. The first one is called service and the second one is called card. Between the two tables, there is a relation via the service_id column on the card table. I want to retrieve all cards which are related to a service with a specific name.

enter image description here

My wrong code :

$data = request()->get('s');
$search = card::where('service_id', 'like', "%{$data}%")
    ->paginate($this->paginateNum);

How can I do it ?

Upvotes: 0

Views: 648

Answers (1)

Tohid Dadashnezhad
Tohid Dadashnezhad

Reputation: 1938

You are looking for whereHas($relation, $callback), which lets you search on a related table:

$data = request()->get('s');

$search = card::whereHas('service', function ($query) use ($data) {
    $query->where('name', 'like', "%{$data}%");
})->paginate($this->paginateNum);

Upvotes: 1

Related Questions