Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel search 'LIKE' query in two tables

I'm currently trying to set up a search bar that filters the results of two tables, books and categories.

I have setup relationships for both models where:

Book.php (Model) (table: id, b_name, b_author, cat_id)

public function bookCategory()
{
  return $this->belongsTo('Category', 'cat_id', 'id');
}

Category.php (Model) (table: id, cat_name)

public function book()
{
  return $this->hasMany('Book', 'cat_id', 'id');
}

BookController.php

public function getFilterBooks($input)
{
  $books = Book::with('bookCategory')->where('**cat_name at category table**. 'LIKE', '%' . $input . '%'')->get();

  return Response::json($books);
}

But obviously this won't work. The reason I'm doing this is because I want to allow users to use the same search bar to filter different columns (which I know how to do it in one table, but not two or more).

like image 825
Robert M. Tijerina Avatar asked Jan 09 '23 21:01

Robert M. Tijerina


1 Answers

You can use that.

Book::whereHas('bookCategory', function($q) use ($input)
{
    $q->where('cat_name', 'like', '%'.$input.'%');

})->get();

See more in http://laravel.com/docs/4.2/eloquent#querying-relations

EDIT:

Book::with('bookCategory')->whereHas('bookCategory', function($q) use ($input)
    {
        $q->where('cat_name', 'like', '%'.$input.'%');

    })->get();

You get cat_name from relation.

like image 87
vitalik_74 Avatar answered Jan 11 '23 20:01

vitalik_74