Skip to content
This repository has been archived by the owner on Feb 8, 2022. It is now read-only.

Commit

Permalink
Implements business logic to search for products
Browse files Browse the repository at this point in the history
  • Loading branch information
victorhqc committed Aug 6, 2019
1 parent de1d018 commit 8bb24a6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
14 changes: 12 additions & 2 deletions app/Http/Controllers/ProductsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,24 @@ class ProductsController extends Controller {
public function showProducts(Request $request) {
$user = $request->user();

// TODO: Se debería de implementar un páginado en algún momento.
$products = Product::all();
$products = $this->getProducts($request);

return view('products', [
'isAdmin' => isset($user) ? $user->is_admin() : false,
'products' => $products,
'email_img' => isset($user) ? $user->email_gravatar_url(30) : '',
'email' => isset($user) ? $user->email : '',
'search' => $request->input('search'),
]);
}

private function getProducts(Request $request) {
$needle = $request->input('search');

if (!isset($needle) || !$needle) {
return Product::all();
}

return Product::searchBy(trim($needle));
}
}
16 changes: 16 additions & 0 deletions app/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Product extends Model
{
Expand All @@ -17,4 +18,19 @@ class Product extends Model
* @var string
*/
public $keyType = 'string';

public static function searchBy(String $needle) {
return DB::table("products")
->join("brands", "products.brand_id", "=", "brands.id")
->join("product_types", "products.product_type_id", "=", "product_types.id")
->select(
"products.*",
"brands.name as brand_name",
"product_types.name as product_type_name"
)
->where("products.name", "like", "%$needle%")
->orWhere("brands.name", "like", "%$needle%")
->orWhere("product_types.name", "like", "%$needle%")
->get();
}
}

0 comments on commit 8bb24a6

Please sign in to comment.