Created
January 21, 2022 04:07
-
-
Save HakamRaza/8085aaadd1ad2307b60747f5f0255406 to your computer and use it in GitHub Desktop.
Implementing Scope inside Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Model; | |
class Merchant extends Model | |
{ | |
//... | |
/** | |
* scope "productAvailable()" that can be use for Merchant instance | |
* filter merchant has product available | |
* @return Builder query | |
*/ | |
public function scopeProductAvailable($query) | |
{ | |
return $query | |
->leftJoin('products', 'merchants.id', '=', 'products.merchant_id') | |
->where('products.availability', '1'); | |
} | |
//... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers\API\Customer; | |
class MerchantController extends Controller | |
{ | |
/* | |
* Methods before implementing scopes | |
*/ | |
// public function index(MerchantRequest $request) | |
// { | |
// $merchantList = Merchant::leftJoin('products', 'merchants.id', '=', 'products.merchant_id') | |
// ->where('products.availability', '1') | |
// ->where(.... | |
// } | |
// public function searchActiveMerchant(MerchantRequest $request) | |
// { | |
// $merchantList = Merchant::leftJoin('products', 'merchants.id', '=', 'products.merchant_id') | |
// ->where('products.availability', '1') | |
// ->where(.... | |
// } | |
/* | |
* Methods after implementing scopes | |
*/ | |
public function index(MerchantRequest $request) | |
{ | |
$merchantList = Merchant::productAvailable() | |
->where(.... | |
} | |
public function searchActiveMerchant(MerchantRequest $request) | |
{ | |
$merchantList = Merchant::productAvailable() | |
->where(.... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
scope is use to compiled repetitive query inside Model class, scope will return Query Builder instance.