Skip to content

Instantly share code, notes, and snippets.

@HakamRaza
Created January 21, 2022 04:07
Show Gist options
  • Save HakamRaza/8085aaadd1ad2307b60747f5f0255406 to your computer and use it in GitHub Desktop.
Save HakamRaza/8085aaadd1ad2307b60747f5f0255406 to your computer and use it in GitHub Desktop.
Implementing Scope inside Laravel
<?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');
}
//...
}
<?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(....
}
}
@HakamRaza
Copy link
Author

scope is use to compiled repetitive query inside Model class, scope will return Query Builder instance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment