Going straight to the point here. I have a search functionality on my List of Items. However, I also want to search all items by category.
Here's what I have done so far. I am really new to laravel and eloquent so please bear with me.
Category Table
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('code', 30);
$table->string('name');
$table->softDeletes();
$table->timestamps();
});
}
Item Table
public function up()
{
Schema::create('items', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->string('code', 30);
$table->string('name');
$table->softDeletes();
$table->timestamps();
});
Schema::table('items', function($table){
$table->foreign('category_id')->references('id')->on('categories');
});
}
Here's my code:
public function search(){
$q = Input::get ( 'q' );
if($q != ""){
$items = Item::with('Category')
->where ( 'name', 'LIKE', '%' . $q . '%' )
->orWhere ( 'code', 'LIKE', '%' . $q . '%' )
->whereHas('Category', function($cat){
$cat->where('name', 'hardware');
})->paginate(1)->setPath('');
$items = $items->appends ( array (
'q' => Input::get ( 'q' )
) );
}else{
$items = Item::orderBy('id', 'desc')->paginate(10);
}
$softDeletesItems = Item::onlyTrashed()->get();
return view('item.index', compact('items', 'softDeletesItems'));
}
is there a way for me to do a orWHere('category.name', 'LIKE', '%'. $q .'%')?
->orWhere ( 'categories.name', 'LIKE', '%' . $q . '%' )?